How can I mock an ES6 module import using Jest?
Asked Answered
P

10

487

I want to test that one of my ES6 modules calls another ES6 module in a particular way. With Jasmine this is super easy --

The application code:

// myModule.js
import dependency from './dependency';

export default (x) => {
  dependency.doSomething(x * 2);
}

And the test code:

//myModule-test.js
import myModule from '../myModule';
import dependency from '../dependency';

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    spyOn(dependency, 'doSomething');

    myModule(2);

    expect(dependency.doSomething).toHaveBeenCalledWith(4);
  });
});

What's the equivalent with Jest? I feel like this is such a simple thing to want to do, but I've been tearing my hair out trying to figure it out.

The closest I've come is by replacing the imports with requires, and moving them inside the tests/functions. Neither of which are things I want to do.

// myModule.js
export default (x) => {
  const dependency = require('./dependency'); // Yuck
  dependency.doSomething(x * 2);
}

//myModule-test.js
describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    jest.mock('../dependency');

    myModule(2);

    const dependency = require('../dependency'); // Also yuck
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

For bonus points, I'd love to make the whole thing work when the function inside dependency.js is a default export. However, I know that spying on default exports doesn't work in Jasmine (or at least I could never get it to work), so I'm not holding out hope that it's possible in Jest either.

Pegues answered 7/11, 2016 at 12:19 Comment(4)
I'm using Babel for this project anyway, so I don't mind continuing to transpile imports to requires for now. Thanks for the heads up though.Pegues
what if i have ts class A and it calls some function lets say doSomething() of class B how can we mock so that class A makes call to mocked version of class B function doSomething()Vivyanne
for those who want to discover this issue more github.com/facebook/jest/issues/936Tonometer
As of 2023 the way to go is the answer from @cdauth, it works. However, I found out that using Vitest will work out-of-the-box, so I will recommend just using Vitest in case you need to cope with ECMAScript Modules. Check more here: vitest.dev/guide/mocking.html#modulesHarmonia
Z
207

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.js
export default 'defaultExport';
export const namedExport = () => {};

// esModule.test.js
jest.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.

Zollie answered 13/3, 2020 at 11:33 Comment(8)
the key that helped me to make it work was this "you can't call jest.mock() inside the test; you must call it at the top level of the module"Oxytocic
The reason that you must have jest.mock at the top of your tests, is internally jest will reorder the jest.mock before the imports. This is why it doesn't matter if yoour jest.mock is before or after your import. By placing it in a function body, it will not function correctly.Carthusian
The __esModule: true made it work where I needed to mock default exports. Otherwise it worked well without that. Thanks for that answer!Gunas
I'm not clear what 'mockedDefaultExport' is supposed to be -- why isn't it a variable like mockFunction vs a string like 'mockFunction'? why not make them both jest.fn()?Cartwheel
@Cartwheel I think it's just illustrating that any export (including the default export) could be a string just as as easily as it could be a function, and it can be mocked in the same wayZollie
Question - can you extract the mocked module to another testUtils file, and call it? Like this ``` // testUtils.ts export const mockNamedExport = () => { jest.mock('./esModule', () => ({ __esModule: true, // this property makes it work default: 'mockedDefaultExport', namedExport: jest.fn(), })); } // test file import {mockNamedExport} from './testUtils'; mockNamedExport(); ```Principal
I found the blog post referenced before I found this post... You are all much smarter than me. Here is the blog post that worked for me He is saying the same thing, I just found it easier to follow. jest.mock('./config', () => ({ __esModule: true, default: null })); is the important bit.Mervinmerwin
This no longer works (at least not with node 18 and jest 29.7.0), which is no big surprise given that this answer is nearly four years old now. What's more surprising is that this problem still doesn't seem to be fixed in jest!Rigatoni
P
298

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.js
export const doSomething = (y) => console.log(y)
// myModule.js
import { doSomething } from './dependency';

export default (x) => {
  doSomething(x * 2);
}
// myModule-test.js
import 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.js
export default (y) => console.log(y)
// myModule.js
import dependency from './dependency'; // Note lack of curlies

export default (x) => {
  dependency(x * 2);
}
// myModule-test.js
import 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
  });
});

Pegues answered 8/11, 2016 at 12:14 Comment(14)
Thanks for sharing. I think the net result is similar to this - but this might be cleaner - https://mcmap.net/q/80972/-how-to-mock-dependencies-for-unit-tests-with-es6-modulesRecommit
That was really helpful...thanks! Here's a useful variation: My dependency was a constant (e.g. import { MY_CONSTANT } from './dependency';) whose value might change over the course of development but which I wanted to keep fixed in my test. In this case using jest.fn() as you did doesn't make sense so, in the test, after using import * ... as you suggest, I simplified the mutation and just used dependency.MY_CONSTANT = 42;.Healy
Why don't you use jest.mock() in your examples ? I don't have the answer, just asking. Your solution works but I don't feel it's clean.Heer
This worked for me, but Flow does not like the mutation of module exports: Error:(101, 3) Flow: assignment of property 'xxx'. Mutation not allowed on exports of "./moduleName".Gaulin
This works, but it's probably not a good practice. Changes to objects outside the scope of the test seem to be persisted between tests. This can later on lead to unexpected results in other tests.Pellet
Instead of using jest.fn(), you could use jest.spyOn() so you can restore the original method later, so it does not bleed into other tests. I found nice article about different approaches here (jest.fn, jest.mock and jest.spyOn): medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c .Phyllous
Just a note: if the dependency is reside on the same file as myModule, it will not work.Chemotaxis
I wonder if Jest team can make this a little less painful, without requiring the hacking around of import *Chemotaxis
it would good to know how this hack really works. I had a hard time explaining this is bad practice since it worked. I almost thought it was NOT allowed (OR should not be allowed). Some insight would help ...Censurable
this way of mocking is fine, as long you resetMock after each test to reset the mutations. e.g afterEach(() => { dependency.mockReset(); });Eternity
I think this won't work with Typescript the object you're mutating is read-only.Norean
This doesn't work with the node experimental modules turned on in package.json with type: module. I got it to work with the babel transpiler.Brouwer
@adredx You can use spyOn. it will work perfectly with typescript and you can restore the original method laterHadfield
How does Jest change/mock the original default or named export when it is imported and jest.mock("package-name") is called?Barbaraanne
B
285

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);
  });
});
Bootery answered 7/11, 2016 at 12:39 Comment(4)
Thanks, but I still can't get it to work with that approach. jest.mock just doesn't seem to be able to mutate the module well enough for other imports to be effected. I'm about to post an answer with another solution, which is kinda close enough to what I'm after.Pegues
@IrisSchaffer in order to have this work with the default export you need to add __esModule: true to the mock object. That's the internal flag used by the transpiled code to determine whether it's a transpiled es6 module or a commonjs module.Soda
Mocking default exports: jest.mock('../dependency', () => ({ default: jest.fn() }))Seigler
Didn't work for me: The module factory of jest.mock() is not allowed to reference any out-of-scope variables.Abjuration
Z
207

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.js
export default 'defaultExport';
export const namedExport = () => {};

// esModule.test.js
jest.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.

Zollie answered 13/3, 2020 at 11:33 Comment(8)
the key that helped me to make it work was this "you can't call jest.mock() inside the test; you must call it at the top level of the module"Oxytocic
The reason that you must have jest.mock at the top of your tests, is internally jest will reorder the jest.mock before the imports. This is why it doesn't matter if yoour jest.mock is before or after your import. By placing it in a function body, it will not function correctly.Carthusian
The __esModule: true made it work where I needed to mock default exports. Otherwise it worked well without that. Thanks for that answer!Gunas
I'm not clear what 'mockedDefaultExport' is supposed to be -- why isn't it a variable like mockFunction vs a string like 'mockFunction'? why not make them both jest.fn()?Cartwheel
@Cartwheel I think it's just illustrating that any export (including the default export) could be a string just as as easily as it could be a function, and it can be mocked in the same wayZollie
Question - can you extract the mocked module to another testUtils file, and call it? Like this ``` // testUtils.ts export const mockNamedExport = () => { jest.mock('./esModule', () => ({ __esModule: true, // this property makes it work default: 'mockedDefaultExport', namedExport: jest.fn(), })); } // test file import {mockNamedExport} from './testUtils'; mockNamedExport(); ```Principal
I found the blog post referenced before I found this post... You are all much smarter than me. Here is the blog post that worked for me He is saying the same thing, I just found it easier to follow. jest.mock('./config', () => ({ __esModule: true, default: null })); is the important bit.Mervinmerwin
This no longer works (at least not with node 18 and jest 29.7.0), which is no big surprise given that this answer is nearly four years old now. What's more surprising is that this problem still doesn't seem to be fixed in jest!Rigatoni
L
73

To mock an ES6 dependency module default export using Jest:

import myModule from '../myModule';
import dependency from '../dependency';

jest.mock('../dependency');

// If necessary, you can place a mock implementation like this:
dependency.mockImplementation(() => 42);

describe('myModule', () => {
  it('calls the dependency once with double the input', () => {
    myModule(2);

    expect(dependency).toHaveBeenCalledTimes(1);
    expect(dependency).toHaveBeenCalledWith(4);
  });
});

The other options didn't work for my case.

Longsuffering answered 11/8, 2017 at 19:52 Comment(7)
what's the best way to clean this up if I just want to make for one test? inside afterEach? ```` afterEach(() => { jest.unmock(../dependency'); }) ````Backsaw
@nxmohamad In your case, I'd use jest.doMock/jest.dontMock inside that specific test itself, instead of jest.mock/jest.unmock - that's because they are hoisted to the top of the test file, impacting the other tests as well, and that's not what you want, right? Take a look into Jest documentation for more details and examples.Longsuffering
@Longsuffering does doMock actually work in that case ? I'm having very similar issue and it does nothing when I'm trying to jest.doMock inside specific test, where jest.mock for whole module is working correctlyLambart
@Progress1ve you can try using jest.mock with mockImplementationOnce as wellLongsuffering
Yup, that's a valid suggestion, however that requires the test to be the first one and I'm not a fan of writing tests in such a way. I got around those issues by importing external module and using spyOn on specific functions.Lambart
@Progress1ve hmm I meant to place the mockImplementationOnce inside each specific test... anyway, I'm happy you've found a solution :)Longsuffering
Doesn't using mockImplementationOnce still force you to mock the whole module with jest.mock first ?Lambart
G
42

Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
  });
});

And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.

Germanize answered 19/12, 2016 at 19:55 Comment(6)
Thanks for this. Will give it a try. Liked this solution too - https://mcmap.net/q/80972/-how-to-mock-dependencies-for-unit-tests-with-es6-modulesRecommit
What I like about this approach is that it gives you the possibility to provide one manual mock for all occasions in which you want to mock a specific module. I for example, have a translation helper, which is used in many places. The __mocks__/translations.js file simply default exports jest.fn() in something like: export default jest.fn((id) => id)Saw
You can also use jest.genMockFromModule to generate mocks from modules. facebook.github.io/jest/docs/…Uta
One thing to note is that ES6 modules mocked via export default jest.genMockFromModule('../dependency') will have all of their functions assigned to dependency.default after calling `jest.mock('..dependency'), but otherwise behave as expected.Pumphrey
What does your test assertion look like? That seems like an important part of the answer. expect(???)Archie
This is my preferred answer, and I was using it but now I need to have N mocks of the same function, representing N-types of return. (eg: when mocking a function that calls a rest endpoint, have one that returns one status code and content, another that returns a different one etc) How would I do this?Bedrock
S
22

None of the answers here seemed to work for me (the original function was always being imported rather than the mock), and it seems that ESM support in Jest is still work in progress.

After discovering this comment, I found out that jest.mock() does not actually work with regular imports, because the imports are always run before the mock (this is now also officially documented). Because of this, I am importing my dependencies using await import(). This even works with a top-level await, so I just have to adapt my imports:

import { describe, expect, it, jest } from '@jest/globals';

jest.unstable_mockModule('../dependency', () => ({
  doSomething: jest.fn()
}));

const myModule = await import('../myModule');
const dependency = await import('../dependency');

describe('myModule', async () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});
Slip answered 9/2, 2022 at 5:52 Comment(6)
most promising alternative, but: ReferenceError: require is not definedAbjuration
@GabrielAnderson My code doesn't use require, I assume you are transpiling your code to CommonJS.Slip
Worked for me. Order of code, await import, and unstable_mockModule were the keys.Michaeline
@GabrielAnderson if you are using jest with ts-jest to transform typescript you can must also instruct jest which files it should treat as esm. ``` #jest.config.js extensionsToTreatAsEsm: ['.ts'], transform: { '^.+\\.ts$': [ 'ts-jest', { useESM: true, }, ], }, ```Erythroblast
Cool, I'll try latter. But no, I just use vanilla JS, without any parser.Abjuration
This year, I am so grateful I found this!Consistence
M
13

The question is already answered, but you can resolve it like this:

File dependency.js

const doSomething = (x) => x
export default doSomething;

File myModule.js

import doSomething from "./dependency";

export default (x) => doSomething(x * 2);

File myModule.spec.js

jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    doSomething.mockImplementation((x) => x * 10)

    myModule(2);

    expect(doSomething).toHaveBeenCalledWith(4);
    console.log(myModule(2)) // 40
  });
});
Middleoftheroad answered 25/6, 2019 at 9:57 Comment(6)
But "require" is CommonJS syntax - OP was asking about ES6 ModulesZollie
@Zollie thanks for your comment, I updated my answer. BTW same thing in the logic.Middleoftheroad
How can you call .mockImplementation on doSomething before mocking it?Schmuck
I think this answer needs some ellaboration, i have the same question as aboveScare
@T J @Alexander Santos doSomethingis mocked automatically in line 1, which mocks the whole module ../dependency.Landpoor
Yes! I learned that after some works, but this should be noted into the answer. Some of those functionalities are not very explicit for newbiesScare
B
3

I solved this another way. Let's say you have your dependency.js

export const myFunction = () => { }

I create a depdency.mock.js file besides it with the following content:

export const mockFunction = jest.fn();

jest.mock('dependency.js', () => ({ myFunction: mockFunction }));

And in the test, before I import the file that has the dependency, I use:

import { mockFunction } from 'dependency.mock'
import functionThatCallsDep from './tested-code'

it('my test', () => {
    mockFunction.returnValue(false);

    functionThatCallsDep();

    expect(mockFunction).toHaveBeenCalled();

})
Bouldin answered 1/5, 2019 at 20:54 Comment(1)
this isn't valid Jest. you'll receive an error like this: The module factory of jest.mock() is not allowed to reference any out-of-scope variables.Connelley
R
3

I tried all the solutions and none worked or were showing lots of TS errors.

This is how I solved it:

format.ts file:

import camelcaseKeys from 'camelcase-keys'
import parse from 'xml-parser'

class Format {
  parseXml (xml: string) {
    return camelcaseKeys(parse(xml), {
      deep: true,
    })
  }
}

const format = new Format()
export { format }

format.test.ts file:

import format from './format'
import camelcaseKeys from 'camelcase-keys'
import parse from 'xml-parser'

jest.mock('xml-parser', () => jest.fn().mockReturnValue('parsed'))
jest.mock('camelcase-keys', () => jest.fn().mockReturnValue('camel cased'))

describe('parseXml', () => {
  test('functions called', () => {
    const result = format.parseXml('XML')

    expect(parse).toHaveBeenCalledWith('XML')
    expect(camelcaseKeys).toHaveBeenCalledWith('parsed', { deep: true })
    expect(result).toBe('camel cased')
  })
})
Roter answered 6/6, 2022 at 9:19 Comment(1)
having the mock value as parameter worked for me thanks!Idaho
H
-1

I made some modifications on @cam-jackson original answer and side effects has gone. I used lodash library to deep clone the object under test and then made any modification I want on that object. But be ware that cloning heavy objects can have negative impact on test performance and test speed.

objectUndertest.js

const objectUnderTest = {};
export default objectUnderTest;

objectUnderTest.myFunctionUnterTest = () => {
  return "this is original function";
};

objectUndertest.test.js

import _ from "lodash";
import objectUndertest from "./objectUndertest.js";

describe("objectUndertest", () => {
  let mockObject = objectUndertest;

  beforeEach(() => {
    mockObject = _.cloneDeep(objectUndertest);
  });

  test("test function", () => {
    mockObject.myFunctionUnterTest = () => {
      return "this is mocked function.";
    };

    expect(mockObject.myFunctionUnterTest()).toBe("this is mocked function.");
  });
});
Handy answered 29/10, 2022 at 11:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.