Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset Jest mock functions calls count before every test

People also ask

Does Jest reset mocks between files?

You don't have to reset the mocks, as the test are run in parallel, every test file run in its own sandboxed thread. Even mocking JavaScript globals like Date or Math. random only affects the actual test file.

Which method is useful to clean up a mock's usage data between two assertions?

results arrays. Often this is useful when you want to clean up a mocks usage data between two assertions.

How do you spyOn a function in Jest?

To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.


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();
});

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.


You can configure Jest to reset mocks after each test by putting this into your jest.config.js:

module.exports = {
  resetMocks: true,
};

Here is the documentation for this configuration parameter: 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.


You can add the --resetMocks option to the command: npx jest --resetMocks

Automatically reset mock state between every test. Equivalent to calling jest.resetAllMocks()