I’m working on a product in Typescript that uses some external package (written in JS if it matters) via npm. In the test i’d like to mock only one JS file from that package.
How can i do it with Jest?
package.js:
"dependencies": {
...
"@company/product": "1.8.0"
...
someFile.ts:
import * as sdk from "@company/product";
I’ve tried to mock it as follows:
someFile.spec.ts:
...
const prefs: IPrefs = {
some_property: -1
};
jest.mock(
"@company/product/sdk/api/prefs.js",
(): { Prefs: IPrefs } => {
return {
Prefs: prefs
};
}
);
The original "prefs.js" file from the external package looks as follows:
import ... // i can see in the failed test stack trace
export let Prefs = {
...
};
But it’s clearly not mocking as i can see the stack trace from the original "prefs.js" that comes in the external package.
2
Answers
Create a
__mocks__
directory adjacent to thenode_modules
Inside
__mocks__
, replicate the directory structure of the package you are mocking.Inside
__mocks__/company/product/sdk/api/prefs.js
, define the mock implementation for your function:Here,
jest.fn()
creates a mock function that you can control in your tests.