How can I mock an ES6 module import using Jest? How can I mock an ES6 module import using Jest? javascript javascript

How can I mock an ES6 module import using Jest?


Edit: Several years have passed and this isn't really the right way to do this any more (and probably never was, my bad).

Mutating an imported module is nasty and can lead to side effects like tests that pass or fail depending on execution order.

I'm leaving this answer in its original form for historical purposes, but you should really use jest.spyOn or jest.mock. Refer to the jest docs or the other answers on this page for details.

Original answer follows:


I've been able to solve this by using a hack involving import *. It even works for both named and default exports!

For a named export:

// dependency.jsexport const doSomething = (y) => console.log(y)// myModule.jsimport { doSomething } from './dependency';export default (x) => {  doSomething(x * 2);}// myModule-test.jsimport myModule from '../myModule';import * as dependency from '../dependency';describe('myModule', () => {  it('calls the dependency with double the input', () => {    dependency.doSomething = jest.fn(); // Mutate the named export    myModule(2);    expect(dependency.doSomething).toBeCalledWith(4);  });});

Or for a default export:

// dependency.jsexport default (y) => console.log(y)// myModule.jsimport dependency from './dependency'; // Note lack of curliesexport default (x) => {  dependency(x * 2);}// myModule-test.jsimport myModule from '../myModule';import * as dependency from '../dependency';describe('myModule', () => {  it('calls the dependency with double the input', () => {    dependency.default = jest.fn(); // Mutate the default export    myModule(2);    expect(dependency.default).toBeCalledWith(4); // Assert against the default  });});


You have to mock the module and set the spy by yourself:

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);  });});


Fast forwarding to 2020, I found this blog post to be the solution: Jest mock default and named export

Using only ES6 module syntax:

// esModule.jsexport default 'defaultExport';export const namedExport = () => {};// esModule.test.jsjest.mock('./esModule', () => ({  __esModule: true, // this property makes it work  default: 'mockedDefaultExport',  namedExport: jest.fn(),}));import defaultExport, { namedExport } from './esModule';defaultExport; // 'mockedDefaultExport'namedExport; // mock function

Also one thing you need to know (which took me a while to figure out) is that you can't call jest.mock() inside the test; you must call it at the top level of the module. However, you can call mockImplementation() inside individual tests if you want to set up different mocks for different tests.