Jest在合法TypeScript代码中报'missing semicolon error'错误求助
TypeScript + Jest 配置问题解决方案
问题描述
环境:Node.js v16.14.0、npm 8.3.1
从可正常运行的TypeScript+Jest项目复制代码后,当前配置存在以下问题:
- 所有测试中,
let userSvc: UserService;这行的冒号位置被提示「缺少分号」 ./node_modules/.bin/tsc命令可正常执行,但Jest无法正常运行
原配置文件
package.json
{"name": "userservice", "version": "1.0.0", "description": "typescript interview", "main": "index.js", "scripts": {"test": "test"}, "repository": {"type": "git", "url": "git+ssh://git@github.com/deanhiller/userServiceJs.git"}, "author": "Dean", "license": "ISC", "bugs": {"url": "https://github.com/deanhiller/userServiceJs/issues"}, "homepage": "https://github.com/deanhiller/userServiceJs#readme", "devDependencies": {"@babel/core": "7.19.3", "@babel/preset-env": "7.19.4", "@babel/preset-typescript": "7.18.6", "@types/jest": "^29.1.2", "babel-jest": "29.2.0", "jest": "29.2.0", "ts-generic-collections-linq": "1.0.7", "ts-jest": "29.0.3", "typescript": "4.8.4"}}
tsconfig.json
{"compilerOptions": {"experimentalDecorators": true, "target": "es6", "outDir": "dist", "lib": ["dom", "dom.iterable", "esnext"], "sourceMap": true, "allowJs": false, "noImplicitAny": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": false, "jsx": "react-jsx"}, "include": ["src"]}
解决方案
1. 修复测试命令
原 scripts.test 配置为无效的 "test" 命令,修改为调用Jest:
"scripts": { "test": "jest" }
2. 移除冲突依赖
同时安装 babel-jest 和 ts-jest 会导致转换器冲突,保留专门适配TypeScript的 ts-jest,移除Babel相关依赖:
npm uninstall @babel/core @babel/preset-env @babel/preset-typescript babel-jest
3. 添加Jest配置文件
在项目根目录创建 jest.config.js,配置ts-jest预设:
/** @type {import('ts-jest').JestConfigWithTsJest} */ module.exports = { preset: 'ts-jest', testEnvironment: 'node', // 若为浏览器项目可改为 'jsdom' roots: ['<rootDir>/src'], testMatch: ['**/*.test.ts'] };
4. 适配Jest模块系统
Jest默认使用CommonJS模块,原 tsconfig 中 module: "esnext" 会引发兼容问题,修改配置:
"compilerOptions": { // 保留原有其他配置... "module": "CommonJS" }
若需保留ESNext用于生产环境,可创建 tsconfig.test.json 单独配置测试环境:
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "CommonJS" } }
并在 jest.config.js 中指定该配置:
module.exports = { // 其他配置... globals: { 'ts-jest': { tsconfig: 'tsconfig.test.json' } } };
5. 包含测试文件到编译范围
修改 tsconfig.json 的 include 字段,确保测试文件被编译:
"include": ["src", "src/**/*.test.ts"]
完成以上配置后,执行测试命令即可正常运行Jest:
npm run test
内容的提问来源于stack exchange,提问作者Dean Hiller
相关产品推荐
相关产品推荐

