How to Mock an ES6 Module Import using Jest

Last Updated:
Mock ES6 Module in 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!

For a more in-depth look into ES6 Modules take a look at this piece.

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 {
} from './fileWithModuleToMock';

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

And the test file would look like:

import functionToTest from './functionToTest';
import {
} from './fileWithModuleToMock';


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



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.

Take a look at the article on testing with Jest and React Testing Library for a basic overview of unit testing.

Related Posts

Get helpful Jest Pieces right to your inbox

Keep up to date with all helpful bits of Jest snippets and articles.