Home > Enterprise >  How to jest.mock an ES6 module import?
How to jest.mock an ES6 module import?

Time:05-11

I've moved a load of helper methods into a npm published library, but some of them are being mocked in the unit tests and I can't figure out how to mock the new imports.

Throughout my code I am able to successfully refactor .tsx files like so:

FROM:

import { doSomething } from "../../utils/stringUtils";

TO:

import { Utils } from "@mine/my-lovely-libary";
const { doSomething } = Utils;

But in the unit tests in spec.tsx I can't get the mocks to work:

jest.mock("../../utils/stringUtils", () => ({
    ...jest.requireActual("../../utils/stringUtils"),
    doSomething: (date: string) => date.toString(),
}));

I want to do something like this:

import { Utils } from "@mine/my-lovely-libary";
const { doSomething } = Utils;
jest.mock(doSomething);

CodePudding user response:

Have you try to mock like this

jest.mock('@mine/my-lovely-libary', () => ({
    doSomething: () => doSomethingMock,
}));

here doSomething is a method from your npm library

doSomethingMock can be jest.fn() or something like this const doSomethingMock = 'mockTestValue'

  • Related