Jest在使用绝对路径导入组件时会出现“找不到模块”的错误

182

运行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'; 导入应用程序容器。 - Metalik
12
我需要知道如何运行绝对路径,这样我就不必在导入时反复返回多个目录或者在移动文件时更新多个文件。 - Seth McClaine
重要的是要提到这里的jest配置在package.json中。但它也可以在jest.config.json或其他文件中。 - oskrgg
重要的是要提到这里的jest配置在package.json中。但它也可以在jest.config.json或其他文件中。 - undefined
15个回答

1
我想使用的模块之一具有 .cjs 扩展名。 在 jest.config.js 中将 .cjs 添加到 moduleFileExtensions 中,可以解决这个问题。
我的示例 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"],
};


1
这也可能是由于globalSetup文件中存在的绝对导入(或其引用的任何文件)所导致的。
看起来moduleNameMapper不会应用于globalSetup文件。我通过将这些特定文件切换为相对导入来解决了这个问题。

1
这对我解决了问题。
这是我的jest-e2e.json文件:
{
    "moduleFileExtensions": ["js", "json", "ts"],
    "rootDir": "..",
    "globalSetup": "<rootDir>/src/integration-test/setup.ts",
    "globalTeardown": "<rootDir>/src/integration-test/teardown.ts",
    "testEnvironment": "node",
    "testRegex": ".e2e-spec.ts$",
    "transform": {
        "^.+\\.(t|j)s$": "ts-jest"
    },
    "moduleDirectories": ["<rootDir>", "node_modules"],
    "moduleNameMapper": {
        "^src/(.*)$": "<rootDir>/src/$1"
    },
    "testPathIgnorePatterns": [".*\\.e2e\\.ts$"],
    "collectCoverageFrom": ["src/**/*.ts", "!src/private/**/*.resolver.ts"],
    "coveragePathIgnorePatterns": [
        ".*\\.module\\.ts$",
        ".*\\.entity\\.ts$",
        ".*\\.dto\\.ts$",
        ".*\\.interface\\.ts$",
        ".*\\.input\\.ts$",
        ".*\\.config\\.(t|j)s$",
        ".*\\.js$",
        "/dist/",
        "/coverage/",
        "/node_modules/"
    ],
    "coverageDirectory": "./coverage",
    "transformIgnorePatterns": ["node_modules/(?!(node-fetch)/)"]
}

你可以看到我在那里调用了 "setup.ts"。然后我在我的 setup.ts 文件中添加了 "tsconfig-paths/register",就像这样:
require("tsconfig-paths/register") <---- ADDED THIS

import { integrationTestEnvSetup } from "./env-setup"
import { integrationTestSetupStuff } from "./setup-stuff"

/* Code run prior to integration test from ./jest-e2e.json */

const integrationTestSetup = async () => {
    await integrationTestEnvSetup()
    await integrationTestSetupStuff()
}

export default integrationTestSetup

请确保您已经安装了 tsconfig-paths 包。

require("tsconfig-paths/register") 行用于导入 tsconfig-paths 包,这是一个实用程序,允许 Node.js 直接理解 TypeScript 的路径和 baseUrl 选项。通常与诸如 ts-node 之类的工具一起使用,以便在不需要单独编译步骤的情况下直接在 Node.js 中运行 TypeScript 代码。

希望这能帮助其他人!在梳理头发数小时后,我真的很高兴意识到这个方法可行。


0

我之前安装了jest-expo,但没有安装jest。可能与我从Expo中预构建的弹出有关。我不得不运行yarn add jest-expo jest来安装jest,并更新jest-expo。现在我的测试可以运行了。

根据您的设置,可能是npm i jest-expo jestexpo install jest-expo jest。...从他们的文档https://docs.expo.dev/guides/testing-with-jest/中得到了这个想法。


0
尝试将此添加到jest配置中。
"modulePaths": [
  "<rootDir>"
]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接