我正在努力让moduleNameMapper
与NextJS/JavaScript一起工作。对于这个项目,我们没有使用TypeScript。
- 下一篇:12.2.5
- 反应:18.2.0
- 耶稣:29.0.1
- Jest环境jsdom:29.0.1
这是我的jsconfig.json
文件
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*" : ["components/*"],
"@/styles/*" : ["styles/*"],
"@/config/*" : ["config/*"],
"@/hooks/*" : ["hooks/*"],
"@/store/*" : ["store/*"],
}
}
}
我可以在我的项目中做以下事情
import Layout from "@/components/Layout"
import useFetch from "@/hooks/fetch"
然而,当我尝试测试时,我收到了以下消息Cannot find module @/hooks/fetch from pages/account/login/index.js
这是我的jest.config.js
文件
const nextJest = require('next/jest');
const createJestConfig = nextJest({
dir: "./",
});
const customJestConfig = {
moduleDirectories: ["node_modules", "<rootDir>"],
moduleNameMapper: {
"^@/hooks/*": "/hooks/*"
},
testEnvironment: "jest-environment-jsdom",
}
module.exports = createJestConfig(customJestConfig)
正如你所看到的,我正在尝试映射moduleNameMapper
中的路径,但这仍然不起作用。我该如何更正?
我希望对项目和测试项目使用相同的导入格式
非常感谢
通过更改jsconfig.js
文件来解决此问题
const nextJest = require('next/jest');
const customJestConfig = {
moduleDirectories: ["node_modules", "<rootDir>"],
testEnvironment: "jest-environment-jsdom",
};
const createJestConfig = nextJest({
dir: './',
})(customJestConfig);
module.exports = async () =>
{
// Create Next.js jest configuration presets
const jestConfig = await createJestConfig();
// Custom `moduleNameMapper` configuration
const moduleNameMapper = {
...jestConfig.moduleNameMapper,
'^@/(.*)$': '<rootDir>/$1',
};
return { ...jestConfig, moduleNameMapper };
};
来源:https://github.com/vercel/next.js/issues/36682