本文介绍了使用绝对路径导入组件时,Jest 给出“无法找到模块"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行 Jest 时收到以下错误

Receiving the following error when running 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)

index.jsx

import AppContainer from 'src/views/app';

package.json

package.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"
    ]
  },

我运行仅包含树中相对路径的文件的测试正确运行.

My tests that run files that only contain relative paths in the tree run correctly.

澄清一下,我正在寻找如何配置 Jest 使其不会在绝对路径上失败.

To Clarify, I'm looking for how to configure Jest to not fail on absolute paths.

推荐答案

由于在 package.json 中,您有:

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

这意味着您导入的每个模块将首先在 node_modules 中查找,如果未找到,将在 src 目录中查找.

Which says that each module you import will be looked into node_modules first and if not found will be looked into src directory.

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

Since it's looking into src directory you should use:

import AppContainer from 'views/app';

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

Please note that this path is absolute to the src directory, you do not have to navigate to locate it as relative path.

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

OR you can configure your root directory in moduleDirectories inside your pakcage.json so that all your components could be imported as you want it.

这篇关于使用绝对路径导入组件时,Jest 给出“无法找到模块"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 04:29