Yul*_*nKh 5 typescript jestjs ts-jest
我试图解决这个问题已经走进了死胡同。我正在使用以下 TypeScript 配置:
{
"compilerOptions": {
"module": "es2022",
"moduleResolution": "nodenext",
"target": "es2017",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"noImplicitAny": true,
"outDir": "./dist",
"rootDir": "./src",
"typeRoots": [
"./src/types", "./node_modules/@types"],
"allowJs": true,
"strictFunctionTypes": true,
"noImplicitReturns": true
},
"include": ["./src/**/*"],
"exclude": ["node_modules"],
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": true
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的, moduleResolution 设置为nodenext,因此我必须在导入时显式添加文件扩展名,如下所示: import ServerError from '../models/Errors/ServerError.js';。否则,我会收到一条错误消息,指出找不到该模块。
一切工作正常,但是当我启动测试时出现错误: Cannot find module '../models/Errors/ServerError.js' from '../src/services/usersService.ts'。所以基本上 jest 试图找到文件 ServerError.js,但它不存在,因为所有文件都有 .ts 扩展名,所以它应该是 ServerError.ts。如果我尝试将文件中的 .js 更改为 .ts,我也会收到错误。
由于这个问题,我无法完成我的任务,因此我将不胜感激。
Yul*_*nKh 13
最后,经过一些研究并更新我的笑话配置文件后,我成功解决了这个问题。
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
import type { Config } from 'jest';
const config: Config = {
transform: {
'\\.[jt]sx?$': 'ts-jest'
},
globals: {
'ts-jest': {
useESM: true
}
},
moduleNameMapper: {
'(.+)\\.js': '$1'
},
extensionsToTreatAsEsm: ['.ts']
};
Run Code Online (Sandbox Code Playgroud)
通过此配置,一切工作正常。我希望它能帮助别人。
Már*_*son 10
对我来说这成功了:
"moduleNameMapper": {
"^(\\.\\.?\\/.+)\\.js$": "$1",
},
Run Code Online (Sandbox Code Playgroud)
(改编自https://github.com/kulshekhar/ts-jest/issues/1057#issuecomment-1441733977)
| 归档时间: |
|
| 查看次数: |
3941 次 |
| 最近记录: |