查找文件的JEST模块NameMapper:"解析器:未定义

2022-06-18 00:00:00 reactjs javascript jestjs package.json

我在路径src/components/text下的component文件夹中有一个文本文件(其中包括)

但是,当使用webpack别名import Text from "components/text";时,Jest找不到此文件。

我尝试添加到package.json


"jest": {
    "globals": {
      "NODE_ENV": "test"
    },
    "transform": {
      "\.[jt]sx?$": "babel-jest"
    },
    "verbose": false,
    "rootDir": ".",
    "collectCoverageFrom": [
      "**/*.{js,jsx,ts,tsx}",
      "!**/*.d.ts"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx",
      "ts",
      "tsx"
    ],
    "moduleNameMapper": {
      "\.(css|less|scss|sass|svg)$": "identity-obj-proxy",
      "^components/(.*)$": "<rootDir>/src/components/$1",
      "^assets/(.*)$": "<rootDir>/src/assets/$1",
      "^utils/(.*)$": "<rootDir>/src/utils/$1",
      "^styles/(.*)$": "<rootDir>/src/styles/$1"
      "/^locales/(.*)$/": "<rootDir>/src/locales/$1",
    },
    "testMatch": [
      "**/*.{spec,test}.{js,jsx,ts,tsx}"
    ],
    "modulePathIgnorePatterns": [
      "./dist"
    ],
    "transformIgnorePatterns": [
      "/node_modules/(?!(@opt-ui|@equinor))"
    ],
    "coverageDirectory": "<rootDir>/tests/coverage/"
  }

但我收到错误:

Test suite failed to run

    Configuration error:
    
    Could not locate module components/text mapped as:
    /Users/olahalvorsen/cssu-dashboard-client/src/components$1.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/^components/(.*)$/": "/Users/olahalvorsen/cssu-dashboard-client/src/components$1"
      },
      "resolver": undefined
    }

因此,模块NameMapper中的"^components/(.*)$": "<rootDir>/src/components/$1"解决了上面的第一个问题:)

但现在我收到另一个错误:

FAIL  src/pages/errorpage/tests/error.test.jsx
  ● Test suite failed to run

    Cannot find module 'locales' from 'src/utils/helpers/helpers.js'

    Require stack:
      src/utils/helpers/helpers.js
      src/components/text/index.jsx
      src/pages/errorpage/error.jsx
      src/pages/errorpage/tests/error.test.jsx

      29 | import { nb, enGB } from "date-fns/locale";
      30 | 
    > 31 | import translations from "locales";
         | ^
      32 | 
      33 | export const capitalize = string => {
      34 |   if (typeof string === "string") {


我更新了上面的Package.json。区域设置的相对目录是src/locales。这不应该起作用吗:

  "moduleNameMapper": {
      "^locales/(.*)$": "<rootDir>/src/locales$1",

我尝试使用:"/^locales/(.*)$/": "<rootDir>/src/locales/$1"

解决方案是使用:"^locales(.*)$": "<rootDir>/src/locales/$1"


解决方案

根据日志,我猜您的配置是/^components/(.*)$/: "<rootDir>/src/components$1",而您的给定代码是^components(.*)$

假设上面的是正确的,那么您可能需要按如下方式更改以使其正常工作:

{
  "moduleNameMapper": {
    "/^components/(.*)$/": "<rootDir>/src/components/$1" // You missed out `/` before the rest value `$1`
  },
}

相关文章