DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Robert Marshall
Robert Marshall

Posted on • Originally published at robertmarshall.dev on

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.

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›