'How to jest.mock an ES6 module import?
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);
Solution 1:[1]
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'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hakob Sargsyan |