首页 > 解决方案 > 笑话路径映射错误:找不到模块 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

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

标签: javascripttypescriptjestjsbabeljsts-jest

解决方案


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


推荐阅读