node.js - 使用绝对路径导入组件时,Jest 给出“找不到模块”
问题描述
运行 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 配置为不会在绝对路径上失败。
解决方案
我认为您正在寻找:roots或modulePaths和moduleDirectories
您可以添加相对路径和绝对路径。
我会确保包含<rootDir>
在根数组、<rootDir>
modulePaths 数组和node_modules
moduleDirectories 数组中,除非您有充分的理由排除它们。
"jest": {
"roots": [
"<rootDir>",
"/home/some/path/"
],
"modulePaths": [
"<rootDir>",
"/home/some/other/path"
],
"moduleDirectories": [
"node_modules"
],
}
推荐阅读
- apache - 仅显示目录的自动索引
- apache-spark - Spark 配置,org.apache.spark.shuffle.FetchFailedException 连接失败
- apache-superset - 无法使用 Jinja 上下文 url_param 进行查询
- sphinx - SphinxSearch 轮值
- amazon-web-services - Amplify Fetching 太长
- ionic-framework - 离子构建错误任务':app:processDebugGoogleServices'的执行失败
- node.js - ElectronJS 应用程序图标未出现在 Apple App Store Connect 中
- r - R中两个不同节点之间的链接关联矩阵
- python - 使用 SymPy 使用 python 生成分数的图像
- javascript - 如何从 MongoDB 中的复杂数据结构中检索数据?