How to change mock implementation for a single test with Jest?

Sometimes, we want to change mock implementation for a single test with Jest.

In this article, we’ll look at how to change mock implementation for a single test with Jest.

How to change mock implementation for a single test with Jest?

To change mock implementation for a single test with Jest, we can call the mockImplementation method on the function we want to mock in our test.

For instance, we write

import {
  funcToMock
} from './module';
jest.mock('./module');

beforeEach(() => {
  funcToMock.mockImplementation(() => {
    /* default implementation */
  });
});

test('with new mock function', () => {
  funcToMock.mockImplementation(() => {
    /* implementation specific to this test */
  });
  // ...
});

to call funcToMock.mockImplementation with the mock function as a callback to mock funcToMock in the beforeEach callback to provide a mocked version of funcToMock for all tests.

Then in the 'with new mock function' test, we call funcToMock.mockImplementation again with another function to mock the function for this specific test.

Conclusion

To change mock implementation for a single test with Jest, we can call the mockImplementation method on the function we want to mock in our test.