【问题标题】:Jest gives `Cannot find module` when importing components with absolute paths使用绝对路径导入组件时,Jest 给出“找不到模块”
【发布时间】:2018-11-24 13:48:19
【问题描述】:

运行 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

  "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 配置为不会在绝对路径上失败。

【问题讨论】:

  • 试试import AppContainer from './src/views/app';
  • 我需要知道如何运行绝对路径,这样我就不必在导入时退回多个目录或在移动文件时更新尽可能多的文件

标签: node.js reactjs npm jestjs


【解决方案1】:

因为在package.json 你有:

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

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

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

import AppContainer from 'views/app';

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

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

【讨论】:

  • 就我而言,moduleNameMapper 是要走的路,因为我们有 @ 指向一些特定的根目录。
【解决方案2】:

我认为您正在寻找:rootsmodulePathsmoduleDirectories

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

我会确保在根数组中包含&lt;rootDir&gt;,在modulePaths 数组中包含&lt;rootDir&gt;,在moduleDirectories 数组中包含node_modules,除非您有充分的理由排除它们。

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

【讨论】:

    【解决方案3】:

    添加

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

    如果你的 package.json 文件中有 Jest 的配置应该可以工作。

    如果你有一个jest.config.js 文件,你应该添加它,否则 package.json 将被这个配置文件覆盖(并忽略)。所以在你的jest.config.js 文件中:

    module.exports = {
    // ... lots of props
      moduleDirectories: ["node_modules", "src"],
    // ...
    }
    

    【讨论】:

      【解决方案4】:

      添加 __esModule:true 为我解决了这个问题。

      jest.mock('module',()=>({
        __esModule: true,                    // this makes it work
        default: jest.fn()
      }));
      

      希望这对某人有所帮助。虽然这不是很具体的问题。

      【讨论】:

        【解决方案5】:

        对于那些使用 Webpack 和 Babbel 从头开始​​构建的人。 请尝试以下步骤:

        1. 删除 node_modules 文件夹并重新安装。 (这解决了我的问题)。

        2. 这里是设置 Webpack 所需文档的链接,在某些情况下这不是必需的。 Jest Docs Webpack

        3. 这里是一个文档链接,它解释了如何使用 React 设置 Jest(不使用 Create-React-App)。 Jest React Docs

        4。这是一个使用 Jest 进行简单设置的示例。您可以在 package.json 或 Jest 配置文件中进行设置。

        免责声明:这不能回答 OP 问题。但是大多数人会在这里找到用于此问题的关键字。

          "jest": {
        "moduleFileExtensions": ["js", "jsx"],
        "moduleDirectories": ["node_modules"],
        "moduleNameMapper": {
          "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
          "\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
        }
        

        },

        【讨论】:

          【解决方案6】:

          我想使用的模块之一具有.cjs 扩展名。 在jest.config.js 中添加.cjsmoduleFileExtensions 为我解决了这个问题。

          以我的jest.config.js 为例:

          module.exports = {
              moduleNameMapper: {
                  // see: https://github.com/kulshekhar/ts-jest/issues/414#issuecomment-517944368
                  "^@/(.*)$": "<rootDir>/src/$1",
              },
              preset: "ts-jest/presets/default-esm",
              globals: {
                  "ts-jest": {
                      useESM: true,
                  },
              },
              testEnvironment: 'jsdom',
              transform: {
                  '^.+\\.vue$': 'vue3-jest',
              },
              moduleFileExtensions: ['json', 'js', 'jsx', 'ts', 'tsx', 'vue', "cjs"],
              moduleDirectories: ["node_modules"],
          };
          
          

          【讨论】:

            猜你喜欢
            • 2018-10-14
            • 2021-01-09
            • 2022-07-15
            • 2012-08-27
            • 1970-01-01
            • 2022-01-20
            • 1970-01-01
            • 2017-05-05
            相关资源
            最近更新 更多