Hi I am trying to mock a function from a module within my node_modules. The current way I have tried is
import { getPriceImpactForPosition } from "@gmx-io/sdk/utils/fees/priceImpact.js";
import { getBasisPoints } from "@gmx-io/sdk/utils/numbers.js";
// Move these mocks before any imports
jest.mock("@gmx-io/sdk/utils/fees/priceImpact.js", () => ({
getPriceImpactForPosition: jest.fn()
}));
jest.mock("@gmx-io/sdk/utils/numbers.js", () => ({
getBasisPoints: jest.fn()
}));
but when I call .mockReturnValue on the mock it says it is not a function. I assume that it is not being mocked properly, and is still calling the actual implementation.
Below is my jest.config.js file
/** @type {import('ts-jest').JestConfigWithTsJest} **/
export default {
preset: "ts-jest/presets/js-with-ts-esm",
testEnvironment: "node",
testPathIgnorePatterns: ["/node_modules/", "/dist/"],
transformIgnorePatterns: ["node_modules/(?!(@gmx-io/sdk))"],
extensionsToTreatAsEsm: [".ts", ".jsx"],
transform: {
"^.+\\.(ts|js|mjs)$": ["ts-jest", {
useESM: true,
tsconfig: "tsconfig.json",
}],
},
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1"
}
};
I had a look into the package as well to find the functions that I am trying to mock, it seems that the module itself is using package exports and I am not sure if this will affect mocking in anyway
"exports": {
".": {
"import": "./build/src/index.js",
"require": "./build/src/index.js"
},
"./abis/*": "./build/abis/*",
"./prebuilt/*": "./build/prebuilt/*",
"./utils/*": "./build/src/utils/*",
"./types/*": "./build/src/types/*",
"./configs/*": "./build/src/configs/*"
},
This is currently how I am running my tests
NODE_OPTIONS=--experimental-vm-modules jest --passWithNoTests
Use jest.unstable_mockModule()
instead of jest.mock()
for ESM compatibility.
Ensure mocks are set up before importing the module using await import()
.