gpt4 book ai didi

javascript - Jest 路径映射错误 : Could not locate module xyz mapped as: abc

转载 作者:行者123 更新时间:2023-12-05 04:43:38 27 4
gpt4 key购买 nike

我尝试将 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

对这个有什么想法吗?感谢您的帮助,谢谢 :)

最佳答案

如本post所述,将 moduleDirectories: ['node_modules', './'] 添加到我的 jest 配置将使它工作。我需要删除所有带有前导 @app/ 的导入。很奇怪,所有其他别名都可以正常工作。

关于javascript - Jest 路径映射错误 : Could not locate module xyz mapped as: abc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69572987/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com