我尝试在路径映射中使用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/*
映射到./*
(如错误消息所示),我认为这是正确的。但是不知怎么的,它找不到env配置。
我的项目文件夹结构是:
|./
|-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
对这个有什么想法吗?谢谢你的帮助,谢谢:)
如本文所述,将moduleDirectories: ['node_modules', './']
添加到我的jest配置将使其工作。我需要删除每一个导入与领导@app/
。很奇怪,所有其他别名工作正常。