运行 Jest 时收到以下错误
Cannot find module 'src/views/app' from 'index.jsx'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<anonymous> (src/index.jsx:4:12)
索引.jsx
import AppContainer from 'src/views/app';
包.json
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleDirectories": [
"node_modules",
"src"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
]
},
我运行仅包含树中相对路径的文件的测试运行正确。
为了澄清,我正在寻找如何将 Jest 配置为不会在绝对路径上失败。
原文由 Seth McClaine 发布,翻译遵循 CC BY-SA 4.0 许可协议
由于在
package.json
你有:这表示您导入的每个模块将首先查看
node_modules
如果没有找到,将查看src
目录。由于它正在查看
src
您应该使用的目录:请注意,此路径是
src
目录的绝对路径,您无需导航以将其定位为相对路径。或者,您可以在 pakcage.json 中的 moduleDirectories 中配置根目录,以便可以根据需要导入所有组件。