javascript - Jest 路徑映射錯誤:無法找到模組 xyz,映射為:abc
我嘗試使用 jest(實際上是 ts-jest)搭配路徑映射。不幸的是,它報錯如下:
• Test suite failed to run
Configuration error:
Could not locate module @app/env.local.json mapped as:
./$1.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^@app\/(.*)$/": "./$1"
},
"resolver": undefined
}
13 |
14 | // Utils / Types / Api
> 15 | import config from "@app/env.local.json"
| ^
16 |
17 | const URI_TO_DATABASE = "mongodb://localhost:27017/" + config.DATABASE_NAME
18 |
at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:577:17)
at Object.<anonymous> (database/database.ts:15:1)
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From __tests__/someTest.test.ts.
我的 jest 配置應該已正確配置:
const { pathsToModuleNameMapper } = require("ts-jest/utils")
const { compilerOptions } = require("./tsconfig.json")
module.exports = {
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths)
}
這是我的 tsconfig:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"rootDir": ".",
"baseUrl": ".",
"paths": {
"@app/*": [
"./*"
],
"@api/*": [
"api/*"
],
"@database/*": [
"database/*"
],
"@pdf": [
"pdf/index.ts"
],
"@assets/*": [
"assets/*"
],
"@fonts": [
"assets/fonts/fonts.ts"
],
"@utils": [
"utils/*"
],
"@dbOperations": [
"database/dbOperations"
]
}
},
"include": [
"**/*.ts",
"jest.config.js"
],
"exclude": [
"node_modules"
]
}
我可以想像這個錯誤可能與我的專案資料夾結構和 ts 配置有關。
它將 @app/* 對應到 ./*(如錯誤訊息所示),我認為這是正確的。但不知何故,它無法找到環境配置。
我的專案資料夾結構是:
|./
|-jest.config.js
|-tsconfig.json
|-moreFiles.ts
|-/database/
|--database.ts <-- imports `@app/env.local.json` and gets called anywhere in chain by jest tests
|-/__tests__/
|--someTest.test.ts
|-env.local.json
對這個有什麼想法嗎?感謝你的幫忙,謝謝 :)
答案#1
如本文所述,將 moduleDirectories: ['node_modules', './'] 添加到我的 jest 配置中將使其正常運行。我需要刪除所有以 @app/ 開頭的導入。相當奇怪,其他別名都能正常工作。