How to mock an ES6 module import using Jest?

Sometimes, we want to mock an ES6 module import using Jest.

In this article, we’ll look at how to mock an ES6 module import using Jest.

How to mock an ES6 module import using Jest?

To mock an ES6 module import using Jest, we can call the jest.mock method.

For instance, we write:

import myModule from './myModule';
import dependency from './dependency';
jest.mock('./dependency', () => ({
  doSomething: jest.fn()
}))

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

where './dependency' is the path to the module our code imports.

And the function returns an object that has the mocked items of the dependency module.

We mock doSomething by setting it to a stubbed function returned by jest.fn.

Then we can call dependency.doSomething as we do in our regular code and check how many times it’s called with toBeCalledWith.

Conclusion

To mock an ES6 module import using Jest, we can call the jest.mock method.