使用Jest与TypeScript遇顶层await报错,求配置解决方案
运行npx jest test时,无论怎么调整配置都会触发以下错误:
error TS1378: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', 'node16', or 'nodenext', and the 'target' option is set to 'es2017' or higher.
我的配置文件如下:
tsconfig.json
{ "ts-node": { "esm": true }, "compilerOptions": { "target": "ESNext", "module": "NodeNext", "allowImportingTsExtensions": true, "moduleResolution": "NodeNext", "noEmit": true, "esModuleInterop": true, "strict": true } }
jest.config.json
{ "preset": "ts-jest/presets/default-esm" }
package.json
{ "name": "my-app", "version": "1.0.0", "type": "module", "scripts": { "start": "node --loader ts-node/esm src/index.ts", "test": "jest test" }, "dependencies": { ... }, "types": "./src/index.d.ts", "devDependencies": { "@babel/preset-env": "^7.23.2", "@types/jest": "^29.5.7", "eslint": "^8.52.0", "eslint-config-prettier": "^9.0.0", "eslint-plugin-jest": "^27.6.0", "eslint-plugin-sort-imports-es6-autofix": "^0.6.0", "eslint-plugin-unused-imports": "^3.0.0", "jest": "^29.7.0", "ts-jest": "^29.1.1", "ts-node": "^10.9.1", "typescript": "^5.2.2" } }
强制ts-jest读取你的TS配置
有时候ts-jest会默认生成自己的TS配置,忽略你写的tsconfig.json,需要在jest.config.json里显式指定:{ "preset": "ts-jest/presets/default-esm", "globals": { "ts-jest": { "tsconfig": "./tsconfig.json" } } }给Jest加上ESM兼容参数
因为你的package.json设置了"type": "module",Jest需要额外参数来启用ESM支持,修改package.json的test脚本:"scripts": { "test": "NODE_OPTIONS=--experimental-vm-modules jest test" }检查测试文件格式
确保所有测试文件都是.ts后缀,并且没有混用CommonJS语法(比如require),保持和项目的ESM规范一致。升级ts-jest(可选)
当前使用的ts-jest@29.1.1和jest@29.7.0版本匹配,但可以尝试升级到同大版本的最新版,修复可能存在的兼容性问题:npm install ts-jest@latest --save-dev验证配置生效
运行npx jest --showConfig,检查输出里的globals.ts-jest.tsconfig是否指向正确的文件,以及module和target配置是否和tsconfig.json一致。
内容的提问来源于stack exchange,提问作者Uri

