我试图解决这个问题已经到了死胡同。我正在使用以下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
}
}
正如您所看到的,moduleSolution被设置为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,我也会得到一个错误。
由于这个问题,我无法完成我的任务,所以如果有任何帮助,我将不胜感激。
最后,在做了一些研究并更新了我的jest配置文件后,我终于解决了这个问题。
/** @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']
};
有了这种配置,一切都很好。我希望它能帮助到别人。
对我来说,这做到了:
"moduleNameMapper": {
"^(\.\.?\/.+)\.js$": "$1",
},
(改编自https://github.com/kulshekhar/ts-jest/issues/1057#issuecomment-1441733977(
我通过在jest.config.json
中添加配置moduleFileExtensions
设置来解决问题;
{
....
"moduleFileExtensions": ["ts", "js"],
....
}
这可以通过使用jest-ts-webcompat-resolver npm包来修复。
npm i jest-ts-webcompat-resolver -D
在您的jest.config.ts
中添加:
"resolver": "jest-ts-webcompat-resolver"