When using Jest for unit testing, creating spies helps track function calls, including the number of times they are invoked and the parameters passed during each call. However, after a test concludes, to ensure the independence and accuracy of each test, it is common to reset or clear these spies. Jest provides several methods to achieve this.
1. mockClear()
mockClear() clears the call history of a mock function without altering its implementation. This means the return value or behavior of the mock function remains unchanged; only the call history is reset.
Example code:
javascriptconst myFunction = jest.fn(); myFunction(); myFunction(); console.log(myFunction.mock.calls.length); // Output 2 myFunction.mockClear(); console.log(myFunction.mock.calls.length); // Output 0
2. mockReset()
mockReset() clears the call history of a mock function and resets its implementation. If special implementations were previously set (e.g., returning specific values), these will be restored to their default state after using mockReset().
Example code:
javascriptconst myFunction = jest.fn(() => "return value"); console.log(myFunction()); // Output "return value" myFunction.mockReset(); console.log(myFunction()); // Output undefined because the implementation is reset
3. mockRestore()
When a mock is created using jest.spyOn(), in addition to clearing call history and resetting implementation, it may be necessary to restore the spied function to its original state. The mockRestore() method reverts the spied function to its initial implementation.
Example code:
javascriptconst utils = { fetchData: () => "original data" }; const spy = jest.spyOn(utils, 'fetchData'); console.log(utils.fetchData()); // Output "original data" spy.mockImplementation(() => "mocked data"); console.log(utils.fetchData()); // Output "mocked data" spy.mockRestore(); console.log(utils.fetchData()); // Output "original data"
In practical testing, these methods are typically used within afterEach or beforeEach hooks to ensure test independence and clarity.
Example code:
javascriptdescribe('myFunction tests', () => { const myFunction = jest.fn(); afterEach(() => { myFunction.mockReset(); }); test('test 1', () => { myFunction(); expect(myFunction).toHaveBeenCalled(); }); test('test 2', () => { expect(myFunction).not.toHaveBeenCalled(); }); });