![](/img/trans.png)
[英]TypeScript + Babel + Jest not using moduleNameMapper for less files
[英]Next.js + Jest moduleNameMapper without TypeScript
我正在努力让moduleNameMapper
与 NextJS / JavaScript 一起工作。 对于这个项目,我们没有使用 TypeScript。
这是我的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)
如您所见,我正在尝试 map 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 };
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.