Javascript

How to reset Jest mock functions calls count before every test

19 September 2026 · 9 min read

How to reset Jest mock functions calls count before every test

Testing JavaScript code, especially with frameworks like React, often involves using Jest for unit and integration tests. A crucial aspect of effective testing is verifying that functions are called as expected. Jest mock functions are invaluable for this purpose, allowing us to track calls, arguments, and return values. However, a common challenge arises when you need to ensure a clean slate before each test: How do you effectively reset Jest mock functions calls count before every test? Without properly resetting mock function state, you risk your tests becoming unreliable and producing false positives or negatives. This article will guide you through various methods to reset your Jest mocks, ensuring your tests remain accurate, predictable, and maintainable, ultimately leading to more robust and reliable code.

Understanding Jest Mock Functions

Jest mock functions provide a way to simulate the behavior of functions in your code, allowing you to isolate units of code for testing. They are particularly useful when dealing with dependencies like API calls, database interactions, or other external services. By mocking these dependencies, you can control their behavior and verify that your code interacts with them correctly. Jest provides several methods for creating mock functions, including jest.fn(), jest.spyOn(), and jest.mock(). Each of these methods serves a different purpose, but they all share the ability to track how many times the mock function was called, what arguments it was called with, and what it returned.

The jest.fn() method creates a brand new mock function. jest.spyOn() takes an existing object and replaces one of its methods with a mock function, allowing you to track calls to the original method while still allowing it to execute. jest.mock() is used to mock entire modules, replacing them with mock implementations. Understanding these different mocking techniques is crucial for writing effective and targeted tests. For instance, using jest.spyOn() can be beneficial when you want to observe the behavior of a real function but still need to assert on its call count and arguments. According to the Jest documentation, utilizing mock functions effectively contributes to writing testable and maintainable JavaScript code [Jest Mock Functions Documentation].

Failing to manage the state of your mock functions between tests can lead to test pollution, where the results of one test bleed into subsequent tests. This can make your tests flaky and unreliable, as they may pass or fail depending on the order in which they are run. By resetting the mock function’s call count and any other relevant state before each test, you ensure that each test is isolated and independent, leading to more reliable and trustworthy test results.

Methods for Resetting Mock Function Calls

Several methods exist to reset Jest mock functions calls count before every test. Each approach has its own advantages and disadvantages, depending on your specific testing needs and code structure. The most common methods include mockClear(), mockReset(), and mockRestore(). Choosing the right method depends on whether you want to simply clear the call history, reset the mock implementation, or completely restore the original function.

The mockClear() method is the simplest approach. It clears the call history of the mock function, resetting the mock.calls, mock.instances, and mock.results properties. However, it does not affect the mock function’s implementation. This means that the mock function will continue to behave as it was originally defined, but its call count will be reset to zero. This is often the preferred method when you only need to clear the call history and don’t want to change the mock function’s behavior.

The mockReset() method goes a step further than mockClear(). In addition to clearing the call history, it also resets the mock function’s implementation to its original state. This means that if you defined a custom implementation for the mock function, it will be replaced with the default mock implementation. This method is useful when you want to ensure that the mock function starts with a clean slate, both in terms of its call history and its behavior. According to Kent C. Dodds, a prominent figure in the testing community, using mockReset() can help prevent unexpected behavior in your tests [Kent C. Dodds on Mocking].

The mockRestore() method is specifically designed for mock functions created with jest.spyOn(). It completely removes the mock function and restores the original function that was spied on. This method is useful when you want to undo the mocking and return the object to its original state. It’s important to note that mockRestore() can only be used on mock functions created with jest.spyOn(); attempting to use it on a mock function created with jest.fn() or jest.mock() will result in an error.

Implementing Resetting in Jest Tests

Now, let’s look at how to implement these methods in your Jest tests to reset Jest mock functions calls count before every test. The most common approach is to use the beforeEach() hook, which runs before each test case. This ensures that the mock function is reset before each test, regardless of whether the previous test modified its state.

Here’s an example of how to use beforeEach() with mockClear():

describe('MyComponent', () => { const myFunction = jest.fn(); beforeEach(() => { myFunction.mockClear(); }); it('should call myFunction once', () => { // Code that calls myFunction expect(myFunction).toHaveBeenCalledTimes(1); }); it('should call myFunction with specific arguments', () => { // Code that calls myFunction expect(myFunction).toHaveBeenCalledWith('argument1', 'argument2'); }); }); 

In this example, myFunction.mockClear() is called before each test, ensuring that the call history is reset. This prevents the call count from accumulating across tests. Similarly, you can use mockReset() or mockRestore() within the beforeEach() hook, depending on your specific needs. For example:

describe('MyComponent', () => { const myModule = require('../myModule'); const mySpy = jest.spyOn(myModule, 'myFunction'); beforeEach(() => { mySpy.mockRestore(); }); it('should call myFunction once', () => { // Code that calls myModule.myFunction expect(mySpy).toHaveBeenCalledTimes(1); }); }); 

This example uses mockRestore() to completely remove the mock function and restore the original function. This is particularly useful when you want to ensure that the original function is used in subsequent tests.

Here’s a featured snippet optimized paragraph:

To reset Jest mock functions calls count before every test, use the beforeEach() hook in your test suite. Inside the beforeEach() block, call mockClear() on your mock function to clear its call history, mockReset() to also reset its implementation, or mockRestore() to completely remove the mock and restore the original function (only applicable for spies created with jest.spyOn()). This ensures that each test starts with a clean slate and avoids test pollution.

Best Practices and Considerations

While resetting mock function calls is essential for reliable testing, it’s important to follow best practices to avoid common pitfalls. One common mistake is to forget to reset the mock function, leading to flaky tests. To prevent this, always include a beforeEach() hook that resets the mock function before each test. Consider using a linter rule to enforce this practice.

Another important consideration is the scope of your mock functions. If you define a mock function within a describe() block, it will be accessible to all tests within that block. This can be useful for sharing mock functions across multiple tests, but it also means that you need to be extra careful to reset the mock function before each test. Alternatively, you can define mock functions within each it() block, which limits their scope and reduces the risk of test pollution.

It’s also important to choose the right method for resetting your mock functions. Using mockClear() is generally sufficient when you only need to clear the call history. However, if you need to reset the mock function’s implementation, use mockReset(). And if you’re using jest.spyOn(), use mockRestore() to completely remove the mock and restore the original function. Improper usage of these methods can lead to unexpected behavior and unreliable tests.

  • Always use beforeEach() to reset mock functions.
  • Choose the appropriate reset method (mockClear(), mockReset(), or mockRestore()).
  • Consider the scope of your mock functions.

For larger projects with many tests, consider creating utility functions to handle mock resetting. This can help ensure consistency and reduce boilerplate code. For example, you could create a function that takes a mock function as an argument and resets it using the appropriate method. This function can then be used in your beforeEach() hooks to simplify your test code.

Here are steps to reset a mock function:

  1. Identify the mock function you want to reset.
  2. Determine the appropriate reset method (mockClear(), mockReset(), or mockRestore()).
  3. Add a beforeEach() hook to your test suite.
  4. Call the reset method on the mock function within the beforeEach() hook.
  5. Verify that the mock function is reset before each test.

Click here for more testing tips. - Test isolation is key to reliable results.

  • Consistent mocking strategies contribute to maintainable tests.
Infographic here
FAQ: Resetting Jest Mocks -------------------------
**Q: What is the difference between mockClear(), mockReset(), and mockRestore()?**
A: mockClear() clears the call history of the mock. mockReset() clears the call history and resets the mock implementation. mockRestore() removes the mock and restores the original function (only for spies).
**Q: When should I use mockRestore()?**
A: Use mockRestore() when you've used jest.spyOn() and want to completely remove the mock and restore the original function.
**Q: Why are my tests failing even though I'm using mocks?**
A: Ensure you are properly resetting your mocks before each test using beforeEach() and one of the reset methods. Also, verify that your mock implementations are correct.
**Q: Can I reset all mocks at once?**
A: Yes, Jest provides jest.clearAllMocks(), jest.resetAllMocks(), and jest.restoreAllMocks() to apply these operations to all mocks. \[[Jest Global Mocking](https://jestjs.io/docs/jest-objectjestclearmocks)\]
Mastering the art of resetting Jest mock functions is a cornerstone of writing robust and reliable JavaScript tests. By understanding the nuances of mockClear(), mockReset(), and mockRestore(), and by consistently applying them within beforeEach() hooks, you can ensure that your tests remain isolated, predictable, and trustworthy. Neglecting this crucial aspect can lead to test pollution, flaky results, and ultimately, a false sense of security about the quality of your code. Embrace these techniques, and elevate your testing practices to new heights. Now, go forth and write tests that inspire confidence! Explore further topics like advanced mocking techniques and integration testing strategies to continue refining your skillset.

Question & Answer :
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?

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

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