Week 5 - Session 2 - Test Doubles & jest.fn()

blog image source
A unit test should test one piece of functionality only, where the code will almost always interact with other objects and functions, we need to isolate our System Under Test (SUT) from external code. Isolation is important because; don’t want to indirectly test dependencies, broken dependencies could lead to false negatives in tests, dependencies may have side-effects, and helps us write SOLID code. This is where test double comes in.

A test double is an object that can stand in for a real object in a test (think stunt doubles), or where you replace a production object for testing purposes. Common types of Test Doubles:
  • Stubs: mock with some pre-programmed behaviour, object with given properties, function with given return value.
  • Mocks: passed into a function and used to make an assertion in the test.
  • Spies: record interactions with other objects, test if a function has been called (how many times and with what parameters), useful for testing functions with side-effects.
  • Dummy: act as a placeholder - passed around, but never used in a test.
In Jest, doubles are generally always referred to as mocks, doubles are primarily created with jest.fn(), can be invoked like a function, keeps track of function calls, keeps track of instances when used as a constructor, can provide custom return values, and can provide custom implementations.

Jest Mock Functions - https://facebook.github.io/jest/docs/en/mock-functions.html
The Test Double Rule of Thumb - http://engineering.pivotal.io/post/the-test-double-rule-of-thumb/

Popular posts from this blog

Week 9 to 12 - Learning with MCR Codes

Week 9 - Session 1 - The Internet, the Web, HTTP