How to change mock implementation on a per single test basis with Jest and JavaScript?

Sometimes, we want to change mock implementation on a per single test basis with Jest and JavaScript.

In this article, we’ll look at how to change mock implementation on a per single test basis with Jest and JavaScript.

How to change mock implementation on a per single test basis with Jest and JavaScript?

To change mock implementation on a per single test basis with Jest and JavaScript, we call mockImplementation.

For instance, we write

import { funcToMock } from "./somewhere";
jest.mock("./somewhere");

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

test("test", () => {
  funcToMock.mockImplementation(() => {
    //...
  });
});

to call funcToMock.mockImplementation with a function that has the implementation of the funcToMock function we’re mocking.

Conclusion

To change mock implementation on a per single test basis with Jest and JavaScript, we call mockImplmentation.