运行jest时无法解析Typescript路径?

aurhwmvo  于 2022-12-08  发布在  Jest
关注(0)|答案(3)|浏览(416)

尝试将convert this project转换为使用these instructions的jest。除了使用paths配置的文件之外,我的所有功能都正常:

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

运行测试时,似乎import语句未解析,并记录了以下情况:

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

ybzsozfc

ybzsozfc1#

我想解析从~/开始到我的<baseUrl>/<moduleName>的模块路径。
感谢OJ Kwon链接我解决了它(给予他点)。

tsconfig.json文件名

请参阅模块解析路径Map文档

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

jest配置

然后我们需要告诉jest也解析路径。

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

vmjh9lq92#

将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>'
    ],
}

还要确保您的tsconfig.json文件有一个paths字段,如下所示:

{
  "compilerOptions": {
    ....
    "paths": {
      "src/*": ["src/*"]
    }
  },
}
mwkjh3gx

mwkjh3gx3#

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

相关问题