A magical jest problem
jest.mock("lib/store", () => ({
jotaiStore: jest.fn(),
}));
This code will throw an error
Cannot find module 'lib/store' from 'atoms/imagePreview.test.ts'
However, I also wrote it in jext.config.js, printed the exported configuration at the end, and 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", // 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 next jest version of swc, defining moduleNameMapper
directly inside createJestConfig
does not work, 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