【发布时间】:2021-02-25 05:13:47
【问题描述】:
我在路径下的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"
【问题讨论】:
标签: javascript reactjs jestjs package.json