記一個神奇的 jest 問題
jest.mock("lib/store", () => ({
jotaiStore: jest.fn(),
}));
這樣寫會報錯
Cannot find module 'lib/store' from 'atoms/imagePreview.test.ts'
但是也在 jext.config.js 內寫入了,打印了最後導出的配置,發現並沒有成功加載
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", // 請替換為實際的路徑
},
},
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);
最後發現原因:
在配置 jest.config.js
時候,因為是 next jest 版本的 swc,直接在 createJestConfig
內部定義 moduleNameMapper
是不生效的,要配置在 customJestConfig
內部
希望對碰到此問題的人有所幫助
此文由 Mix Space 同步更新至 xLog
原始鏈接為 https://www.prajnax.com/posts/default/nextJest_moduleNameMapper_not_work