javascript - 笑话路径映射错误:找不到模块 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.
我的笑话配置应该正确配置:
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
对这个有什么想法吗?感谢您的帮助,谢谢:)
解决方案
如本文所述,添加到我的moduleDirectories: ['node_modules', './']
jest 配置中即可。我需要使用前导删除每个导入@app/
。很奇怪,所有其他别名都可以正常工作。
推荐阅读
- java - 为什么 AbstractOwnableSynchronizer.exclusiveOwnerThread 未声明为 volatile?
- javascript - 在下拉列表中控制月份年份
- sapui5 - 智能表扩展到 2 个实体集?
- javascript - 如何将新创建的按钮的值作为 Javascript 变量?
- .net - 将应用程序的 windows 窗体保留在应用程序中,并阻止启动另一个窗体已经打开一个窗体
- python - 为什么 ALTER 命令不适用于 sqlalchemy 但适用于 pgAdmin?
- c# - 按列表中的嵌套对象过滤
- c# - 如何从 C# 中的嵌套循环写入多维数组?
- android - FAB Behavior 防止 RecyclerView 项目被点击
- laravel - 如何通过回答安全问题手动重置密码而不发送电子邮件(Laravel/Vuejs)