How to Mock an ES6 Module Import using Jest

robmarshall

Robert Marshall

Posted on July 14, 2022

How to Mock an ES6 Module Import using Jest

This article was originally posted (and is more up to date) at https://robertmarshall.dev/blog/how-to-mock-an-es6-module-import-using-jest/


What is an ES6 Module?

ES Modules are the ECMAScript standard for working with modules. Node has used this standard for a while, and browsers have only recently (2016) started using ES6. ES6 functions are the same as regular functions with syntactic sugar. So they can be mocked in the same way!

How to Mock an ES6 Module

The jest.mock function is used to mock an ES6 module import with Jest. The initial function would look like:

// ./functionToTest.js
import {
    es6ModuleToMock,
    es6ModuleToReturnThing
} from './fileWithModuleToMock';

export const functionToTest = () => {
    const value = es6ModuleToReturnThing();
    es6ModuleToMock(value);
};

Enter fullscreen mode Exit fullscreen mode

And the test file would look like:

import functionToTest from './functionToTest';
import {
    es6ModuleToMock,
    es6ModuleToReturnThing
} from './fileWithModuleToMock';

jest.mock('./fileWithModuleToMock');

test('example of how to mock an ES6 module', () => {
    const mockValue = 'mock-value';
    es6ModuleToReturnThing.mockReturnValue(mockValue);

    functionToTest();

    expect(es6ModuleToMock).toBeCalledWith(mockValue);
});
Enter fullscreen mode Exit fullscreen mode

What we are doing is importing the particular functions that need to be mocked, and then mocking the whole file with Jest. This allows us to work with different functions run different mocks on them.

馃挅 馃挭 馃檯 馃毄
robmarshall
Robert Marshall

Posted on July 14, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related