我在使用TypeScript项目时,使用ES模块和
import
语法的jest测试不顺利。最初项目是使用commonjs编写的,jest测试可以正常运行。但是后来为了学习目的,我决定切换到ES模块,但jest不开心 ヽ(`Д´)ノ。
我正在使用的工具有: typescript, jest, ts-jest
问题出现在import
语法上。
以下是我尝试过的代码。// projectRoot/src/app.ts
export default someFunction = (): void => {
// some code
}
如果// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app'; // without file extension
/* This execute perfectly fine */
但是// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app.ts' // with .ts
/*
● Test suite failed to run
__tests__/app.test.ts:1:25 - error TS2691: An import path cannot end with a '.ts' extension. Consider importing '../src/app' instead.
1 import information from '../src/app.ts';
*/
并且
// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app.js'; // with .js
/*
● Test suite failed to run
Cannot find module '../src/app.js' from '__tests__/app.test.ts'
*/
如上例,jest(或者可能是ts-jest?)对于使用扩展名(这对于ES模块是必需的)导入模块时不太友好。
我在网上进行了一些搜索,但似乎jest 文档 对于ES模块并不支持。同样,ts-jest也是如此,根据这个 问题
我的项目结构:
/projectRoot
├── /src/app.ts
├── /__tests__/app.test.ts
package.json文件中有一个值"type": "module"
tsconfig.json:
{
"compilerOptions": {
"target": "ES2015",
"module": "ESNEXT",
"outDir": "./build",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["./src"],
"exclude": ["node_modules", "**/*.test.ts"]
}
jest.config.js
export default {
"roots": [
//"<rootDir>/src"
"<rootDir>"
],
"testMatch": [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
"preset": "ts-jest",
"testEnvironment": 'node'
}
请帮忙。谢谢。