Record a magical jest problem
jest.mock("lib/store", () => ({
jotaiStore: jest.fn(),
}));
Writing like this will cause an error
Cannot find module 'lib/store' from 'atoms/imagePreview.test.ts'
But it is also written in jext.config.js, printing the exported configuration at the end, and it is found that it was not successfully loaded
const nextJest = require("next/jest");
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: "./",
});
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
testEnvironment: "jest-environment-jsdom",
globals: {
"ts-jest": {
tsconfig: "<rootDir>/tsconfig.json", // Please replace with the actual path
},
},
moduleNameMapper: {
"^lib/(.*)$": "<rootDir>/lib/$1",
"^app/(.*)$": "<rootDir>/app/$1",
"^atoms/(.*)$": "<rootDir>/atoms/$1",
"^components/(.*)$": "<rootDir>/components/$1",
"^hooks/(.*)$": "<rootDir>/hooks/$1",
},
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
Finally, the reason was found:
When configuring jest.config.js
, because it is the swc version of next jest, defining moduleNameMapper
directly inside createJestConfig
does not take effect, it needs to be configured inside customJestConfig
Hope this helps those who encounter this problem
This article is synchronized and updated to xLog by Mix Space
The original link is https://www.prajnax.com/posts/default/nextJest_moduleNameMapper_not_work