Jest moduleNameMapper查找文件:“解析器”:未定义

jxct1oxe  于 2023-09-28  发布在  Jest
关注(0)|答案(2)|浏览(120)

我在component文件夹中有一个文本文件(以及其他文件),路径为:src/components/text
但是,当使用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
    }

因此,moduleNameMapper中的"^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"

czfnxgou

czfnxgou1#

根据日志,我猜你的配置是/^components\/(.*)$/: "<rootDir>/src/components$1",这与你给定的代码^components(.*)$不同。
假设上面的是正确的,那么你可能需要更改为如下,使其正常工作:

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

5ktev3wc2#

检查您的fileMock.js路径

在我的例子中,我花了很长时间才意识到___test___文件夹有三个下划线,而不是两个。
并检查文件的内容在我的情况下,这是:module.exports = 'test-file-stub'
您还需要先install jest-transform-stub

相关问题