使用绝对路径导入组件时,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 配置为不会在绝对路径上失败。

原文由 Seth McClaine 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

由于在 package.json 你有:

 "moduleDirectories": [
    "node_modules",
    "src"
]

这表示您导入的每个模块将首先查看 node_modules 如果没有找到,将查看 src 目录。

由于它正在查看 src 您应该使用的目录:

 import AppContainer from 'views/app';

请注意,此路径是 src 目录的绝对路径,您无需导航以将其定位为相对路径。

或者,您可以在 pakcage.json 中的 moduleDirectories 中配置根目录,以便可以根据需要导入所有组件。

原文由 Hriday Modi 发布,翻译遵循 CC BY-SA 4.0 许可协议

我认为您正在寻找: rootsmodulePathsmoduleDirectories

您可以添加相对路径和绝对路径。

我会确保在根数组中包含 <rootDir> <rootDir> 在modulePaths数组中包含—,以及 node_modules ,除非你在模块中有一个好的数组排除他们的理由。

 "jest": {
  "roots": [
    "<rootDir>",
    "/home/some/path/"
  ],
  "modulePaths": [
    "<rootDir>",
    "/home/some/other/path"
  ],
  "moduleDirectories": [
    "node_modules"
  ],
}

原文由 twils0 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题