运行 jest 时打字稿路径无法解析?

问题描述 投票:0回答:4

尝试使用这些说明将这个项目转换为笑话。除了使用 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

typescript jestjs tsconfig ts-jest
4个回答
54
投票
我想解析从

~/ 到我的 <baseUrl>/<moduleName>

 的模块 
paths

感谢

OJ Kwon链接我解决了这个问题(给他点)。

tsconfig.json

参见

模块解析路径映射文档

{ "compilerOptions": { "baseUrl": "src", "paths": { "~/*": ["*"] } }, }
笑话配置

然后我们还需要告诉

jest

 来解析路径。它是通过以下配置完成的:

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

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

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

tsconfig.json

 文件具有 
paths
 字段,如下所示:

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

20
投票
jest 无法遵循 tsconfig 的路径映射,因为它是 ts 编译器时间,因此 jest 配置应该具有相应的

modulenamemapper 来解析别名路径。


3
投票
@FranSanchis 的回答确实为我解决了这个问题,我刚刚做了很多更改来满足 2023 年笑话的变化

jest.config.js

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

"compilerOptions": { "target": "es6", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "baseUrl": ".", "paths": { "@/*": ["src/*"] }
    
© www.soinside.com 2019 - 2024. All rights reserved.