Reputation: 4296
I am learning Jest and I see this clearAllMocks function being used, I then check the docs and the description is simply this:
Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function.
Returns the jest object for chaining.
It basically says what you could already figure out by reading the function name. I still can't figure out when should I use this and why is this useful. Could you name an example when this would be good to use?
Upvotes: 2
Views: 10782
Reputation: 11456
This can be set in Jest config file which is equivalent to calling jest.clearAllMocks()
before each test.
https://jestjs.io/docs/configuration#clearmocks-boolean
// jest.config.js
{
// ...rest
"clearMocks": true
}
Upvotes: 6
Reputation: 129
jest.clearAllMocks() is often used during tests set up/tear down.
afterEach(() => {
jest.clearAllMocks()
});
Doing so ensures that information is not stored between tests which could lead to false assertions. Let's say that you have a mock function mockFn and you call the function, you can assert that it's been called 1 time. If in another test you call mockFn again but you have not cleared the mock, it would have been called two times now instead of one.
Upvotes: 9