运行 开玩笑时打字稿路径无法解析?

Typescript paths not resolving when running jest?

正在尝试 convert this project over to jest using these instructions。除了使用 paths 配置的文件外,我一切正常:

"paths": {
      "@fs/*": ["./src/*"], 
      "@test/*": ["./test/*"]
    }

看起来好像在测试时 运行 导入语句没有解析,这被记录在案:

Cannot find module '@fs/container/validation/ValidationContext' from 'Core.spec.ts'

  1 | import { ValidationOptions } from "@fs/container/validation/ValidationOptions";
> 2 | import { ValidationContext } from "@fs/container/validation/ValidationContext";
    | ^
  3 | import { ValidationContainer } from "@fs/container/validation/ValidationContainer";
  4 | 
  5 | import { Core1 } from "@test/core/Core1";

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
  at Object.<anonymous> (test/core/Core.spec.ts:2:1)

有没有办法让 jest/ts-jest 在解析导入时包含 @paths

jest 不能接受 tsconfig 的路径映射,因为它是 ts 编译器时间,所以 jest 配置应该有相应的 modulenamemapper 来解析别名路径。

我想将以 ~/ 开头的模块 paths 解析为我的 <baseUrl>/<moduleName>

感谢link我解决了(给他点)

tsconfig.json

module-resolution path-mapping doc

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "~/*": ["*"]
    }
  },
}

开玩笑配置

然后我们还需要告诉 jest 解析路径。使用以下配置完成:

"moduleNameMapper": {
  "~/(.*)": "<rootDir>/src/"
},

在根项目文件夹中添加 jest.config.js,内容如下。

const { pathsToModuleNameMapper } = require('ts-jest/utils')
const { compilerOptions } = require('./tsconfig')
module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
    modulePaths: [
        '<rootDir>'
    ],
}