How to reset Jest mock functions calls count before every test
jest.clearAllMocks();
didn't clear all the mocks actually for me.
afterEach(() => {
jest.restoreAllMocks();
});
helped me finally clear the spy on jest
As @AlexEfremov pointed in the comments. You may want to use clearAllMocks
after each test:
afterEach(() => {
jest.clearAllMocks();
});
Take in mind this will clear the call count of every mock function you have, but that is probably the right way.
One way I found to handle it: to clear mock function after each test:
To add to Sum.test.js:
afterEach(() => {
local.getData.mockClear();
});
If you'd like to clear all mock functions after each test, use clearAllMocks
afterEach(() => {
jest.clearAllMocks();
});
You can configure Jest to reset or clear mocks after each test by putting one of these parameters this into your jest.config.js
:
module.exports = {
resetMocks: true,
};
or
module.exports = {
clearMocks: true,
};
Here is the documentation:
https://jestjs.io/docs/en/configuration#resetmocks-boolean
resetMocks [boolean]
Default: false
Automatically reset mock state before every test. Equivalent to calling jest.resetAllMocks() before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation.
https://jestjs.io/docs/configuration#clearmocks-boolean
clearMocks [boolean]
Default: false
Automatically clear mock calls, instances and results before every test. Equivalent to calling jest.clearAllMocks() before each test. This does not remove any mock implementation that may have been provided.