ChatGPT解决这个技术问题 Extra ChatGPT

How to reset Jest mock functions calls count before every test

I'm new to Jest, I'm trying to use it for testing if a function was called or not. I noticed the mock.calls.length is not resetting for every test but accumulating. How can I make it 0 before every test? I don't want my next tests depends on the results of the previous.

I know there is beforeEach in Jest - should I use it? What is the best way to reset mock.calls.length? Thank you.

A code example:

Sum.js:

import local from 'api/local';

export default {
  addNumbers(a, b) {
    if (a + b <= 10) {
      local.getData();
    }
    return a + b;
  },
};

Sum.test.js

import sum from 'api/sum';
import local from 'api/local';
jest.mock('api/local');

// For current implementation, there is a difference 
// if I put test 1 before test 2. I want it to be no difference

// test 1
test('should not to call local if sum is more than 10', () => {
  expect(sum.addNumbers(5, 10)).toBe(15);
  expect(local.getData.mock.calls.length).toBe(0);
});

// test 2
test('should call local if sum <= 10', () => {
  expect(sum.addNumbers(1, 4)).toBe(5);
  expect(local.getData.mock.calls.length).toBe(1);
});

A
Alex Efremov

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

Curious if there's a way to do it for all the mocked object's methods. When I try local.mockClear() it doesn't work.
Have you tried to use jest.clearAllMocks()? Docs: jestjs.io/docs/en/jest-object#jestclearallmocks
@AlexEfremov, Thank you so much for the jest.clearAllMocks() function! I have been using mockClear() for jest.mock classes and apparently the mocks were not completely cleared somehow (spy function calls inside mock classes were not cleared). This resulted in really annoying object instance difference errors: Compared values have no visual difference..
To enhance this answer, I updated my jest.config.js property resetMocks: true.
D
Daniel Marín

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.


A
Andrey Vetlugin

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.


I'm not 100% sure on this, but won't this actually RESET the mocks. I.E reset any mock implementations you have? If you are setting the implementation of a mock outside of the actual test, it will be reset by this (if it is equivalent to resetAllMocks() before ech test. The author seems to be looking for a way to clear the call counters, but keep their mock implementation. Again, not 100% sure, but it is my understanding of resetAllMocks.
I agree with @Flux here. The config clearMocks seems to be what the author wants.
Thank for pointing that out, I have extended my answer. Normally one would actually want to reset all mocks for tests to be truly independent.
M
Mifdha Milan

jest.clearAllMocks(); didn't clear all the mocks actually for me.

afterEach(() => {
    jest.restoreAllMocks();
}); 

helped me finally clear the spy on jest


n
nick

clear the individual mocked function after each test, (this may be usefull for someone hitting this url)

import { methodName } from '../Path-to-file-with-methodName';

methodName.mockReturnValue(null );

    describe('my component', ()=> {
      afterEach(() => {
        methodName.mockClear();
      });
      
      it('should call my method on mount', () => {
        const wrapper = mount(<AComponent  {...props} />);
        expect(methodName).toHaveBeenCalledTimes(1);
      })
      it('should call my method on mount again', () => {
        const wrapper = mount(<AComponent  {...props} />);
        expect(methodName).toHaveBeenCalledTimes(1);
      })
    });

 

I
Ivan

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

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