Categories
JavaScript Answers

How to change the behavior of a mocked import with Jest and JavaScript?

Spread the love

Sometimes, we want to change the behavior of a mocked import with Jest and JavaScript.

In this article, we’ll look at how to change the behavior of a mocked import with Jest and JavaScript.

How to change the behavior of a mocked import with Jest and JavaScript?

To change the behavior of a mocked import with Jest and JavaScript, we call the jest.mock method.

For instance, we write

import { methodToMock } from "the-package-to-mock";

jest.mock("the-package-to-mock", () => ({
  methodToMock: jest.fn(),
}));

it("test1", () => {
  methodToMock.mockImplementation(() => "someValue");
});

it("test2", () => {
  methodToMock.mockImplementation(() => "anotherValue");
});

to call jest.mock to mock the methodToMock method in the the-package-to-mock module.

We set methodToMock to the mock function returned by jest.fn.

Then in our tests, we call methodToMock.mockImplementation with a callback mocks the behavior of methodToMock.

Conclusion

To change the behavior of a mocked import with Jest and JavaScript, we call the jest.mock method.

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 *