Reset/Clear with beforeEach/beforeAll and clearAllMocks/resetAllMocks
Assuming we have a global stub or spy that is potentially called mutliple times throughout our tests.
Clearing Jest Mocks with .mockClear(), jest.clearAllMocks() and beforeEach
TODO: Running the examples yarn test src/beforeeach-clearallmocks.test.js
Running the above Jest tests yield the following output:
In this case, mockFn has been called twice, to fix this, we should clear the mock.
We can achieve this as follows by only changing the second file:
Another way to do it is to clearAllMocks, this will mean that between tests, the stubs/mocks/spies are cleared, no matter which mock we’re using.
Technically, we’ve only been changing the 2nd test, although they should be reorderable in principle. In order to run a piece of code before every test, Jest has a beforeEach hook, which we can use as follows.
See Running the examples to get set up, then run: npm test src/beforeeach-clearallmocks.test.js
As per the Jest documentation:
jest.clearAllMocks()
Read more: How long is 4 inches of hair
Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function.
Jest mockReset/resetAllMocks vs mockClear/clearAllMocks
We’ve just seen the clearAllMocks definition as per the Jest docs, here’s the mockReset() definition:
mockFn.mockReset()
Does everything that mockFn.mockClear() does, and also removes any mocked return values or implementations.
This is useful when you want to completely reset a mock back to its initial state. (Note that resetting a spy will result in a function with no return value).
Here’s the explanation:
- mockClear clears only data pertaining to mock calls, which means we get a fresh dataset to assert over with toHaveBeenX methods.
- mockReset resets to mock to its initial implementation, on a spy makes the implementation be a noop (function that does nothing).
I’ve personally not found mockReset’s use case to be too compelling. In situation where one might use resetAllMocks/mockReset, I opt for mockImplementationOnce/mockReturnValueOnce/mockResolvedValueOnce in order to set the behaviour of the stub for a specific test instead of resetting said mock.
Setting a mock/stub/spy implementation with mockImplementation/mockImplementationOnce
We’ve looked at how to make sure call information is cleared between tests using jest.clearAllMocks().
Now we’ll see how to set the implementation of a mock or spy using mockImplementation and mockImplementationOnce.
This is useful when the code under tests relies on the output of a mocked function. In that case, overriding the implementation allows us to create test cases that cover the relevant code paths.
Given a function that returns a string based on the output of another function:
Read more: Pittsburgh mayor salary
We could write the following tests using mockImplementation:
Our tests pass with the following output:
See Running the examples to get set up, then run: npm test src/mockimplementation.test.js
We can override behaviour for a single test, using mockImplementationOnce, which would lead to the following tests
mockImplementationOnce for multiple subsequent calls
mockImplementationOnce can also be used to mock multiple subsequent calls.
See Running the examples to get set up, then run: npm test src/mockimplementationonce-multiple.test.js
The test passes successfully. The output is as follows:
Overriding a synchronous mock/spy/stub’s output with mockReturnValue/mockReturnValueOnce
We can set a mock’s synchronous output using mockReturnValue and mockReturnValueOnce.
As we can see in this example, the order in which we call mockReturnValueOnce on the mock affect the order in which the given values are output. Namely, they’re in the same order, so to mock the first call, use the first mockReturnValueOnce, for the second, the secont call and so on.
What we also observe is that mockReturnValue is used when the outputs set through mockReturnValueOnce are exhausted.
Read more: Better 5 login
See Running the examples to get set up, then run: npm test src/mockreturnvalue.test.js
Overriding an async mock/spy/stub’s output with mockResolvedValue/mockResolvedValueOnce
In a way reminiscent of how mockReturnValue/mockReturnValueOnce can help simplify our tests in the synchronous mock implementation case. mockResolvedValue/mockResolvedValueOnce can help us simplify our tests when setting the implementation of an asynchronous mock.
We can set an asynchronous mock’s resolved output (a Promise that resolves to the value) using mockResolvedValue and mockResolvedValueOnce.
The order in which mockResolvedValueOnce are called on the mock also map to the order of the output of the mock.
mockResolvedValue is used when the outputs set through mockResolvedValueOnce are exhausted.
See Running the examples to get set up, then run: npm test src/mockresolvedvalue.test.js
Running the examples
Clone github.com/HugoDF/jest-set-clear-reset-stub.
Run yarn install or npm install (if you’re using npm replace instance of yarn with npm run in commands).
Further Reading
To understand which assertions can be used on mocks and stubs see the following posts:
- Jest .fn() and .spyOn() spy/stub/mock assertion reference
- Jest assert over single or specific argument/parameters with .toHaveBeenCalledWith and expect.anything()
More foundational reading for Mock Functions and spies in Jest:
- Mock Functions – Jest Documentation
- jest.spyOn(object, methodName) – Jest Documentation
unsplash-logoJose Antonio Gallego Vázquez