Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *