Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 24, 2023 09:01 pm GMT

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 + bexport const substract = (a, b) => a - b;

app

import { sum, substract } from './math.mjs'const sumResult = sum(2, 1);const substractResult = substract(2, 1);

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 methodjest.mock('../math', () => ({    sum: jest.fn(),}));// mock only one method (with implementation)jest.mock('../math', () => ({    sum: jest.fn().mockImplementation(() => '5'),}));// mock all methodsjest.mock('../math', () => ({    sum: jest.fn(),    substract: jest.fn(),}));

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(),    };});

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.


Original Link: https://dev.to/rafaf/mock-imported-modules-in-jest-26ng

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To