How to mock the imports of an ES6 module with Jest and JavaScript?

Sometimes, we want to mock the imports of an ES6 module with Jest and JavaScript.

In this article, we’ll look at how to mock the imports of an ES6 module with Jest and JavaScript.

How to mock the imports of an ES6 module with Jest and JavaScript?

To mock the imports of an ES6 module with Jest and JavaScript, we can call jest.mock.

For instance, we write

import myfunc from "./mymod";
import shortid from "shortid";

jest.mock("shortid");

describe("mocks shortid", () => {
  it("works", () => {
    shortid.mockImplementation(() => 1);
    expect(myfunc()).toEqual(1);
  });
});

to import the real shortid module with

import shortid from "shortid";

Then we use

jest.mock("shortid");

to mock the shortid module.

And then we call shortid.mockImplementation with a callback to mock the return value of the shortid function.

Conclusion

To mock the imports of an ES6 module with Jest and JavaScript, we can call jest.mock.