DEV Community

Rafa FERIAH
Rafa FERIAH

Posted on

Mock imported modules in Jest

When working with JavaScript, it's so common to import external or internal libraries. Sometimes in order to implement modularity and reusability in our project, sometimes to avoid implementing features that have been already developed by a third party.

Today we're gonna see how to mock these libraries when testing the code are using them with Jest suite.

First of all let's suppose we have the following code:

maths.js

export const sum = (a, b) => a + b

export const substract = (a, b) => a - b;
Enter fullscreen mode Exit fullscreen mode

app

import { sum, substract } from './math.mjs'

const sumResult = sum(2, 1);
const substractResult = substract(2, 1);
Enter fullscreen mode Exit fullscreen mode

Given that code, we could have two scenarios:

  1. Mock the full "import", i.e., the full library.
  2. Mock only one of the methods but keep the original code of the other one

So let's see each case:

Mocking the full library

To mock the full library, we just need to mock one of the method (the other one will remain undefined) or we can mock all the methods. The mocking technique is indifferent, it depends on what are we testing.

// mock only one method
jest.mock('../math', () => ({
    sum: jest.fn(),
}));

// mock only one method (with implementation)
jest.mock('../math', () => ({
    sum: jest.fn().mockImplementation(() => '5'),
}));

// mock all methods
jest.mock('../math', () => ({
    sum: jest.fn(),
    substract: jest.fn(),
}));
Enter fullscreen mode Exit fullscreen mode

Mocking only one of the imported methods

As we said before, we can import only one of the methods and keep the original implementation for the rest of the methods

In the following example, we are mocking the substrack method but keep the original implementation of the rest of the library, in this case, the add method

jest.mock('../math', () => {
    const originalMathLib = jest.requireActual('../math');

    return {
        ...originalMathLib,
        substract: jest.fn(),
    };
});
Enter fullscreen mode Exit fullscreen mode

It's very important to include this code at the very top of our testing file, before any other import. These mocks MUST be the firsts lines of our file.

Top comments (0)