Angular 15集成@swc/jest后Jest组件测试出现语法错误求助
Angular 15 + Jest 集成 @swc/jest 报「Expression expected」语法错误解决指南
问题本质
这个错误是因为SWC未正确识别Angular的装饰器语法(比如@Component),将其判定为无效表达式,核心原因是SWC、Jest或TypeScript的配置未适配Angular的编译特性。
关键配置修复方案
1. 修正 .swcrc 配置
确保SWC启用TypeScript装饰器支持,匹配Angular编译需求:
{ "$schema": "https://json.schemastore.org/swcrc", "jsc": { "parser": { "syntax": "typescript", "decorators": true, "dynamicImport": true }, "transform": { "decoratorMetadata": true, "legacyDecorator": true }, "target": "es2020", "loose": true, "externalHelpers": true }, "module": { "type": "es6", "strict": false, "strictMode": true, "lazy": false, "noInterop": false } }
- 开启
decorators和decoratorMetadata是识别Angular装饰器的核心 target设置为es2020匹配Angular 15的默认编译目标
2. 调整 jest.config.mjs 配置
确保Jest使用SWC作为转换器,同时保留Angular测试上下文:
export default { preset: 'jest-preset-angular', transform: { '^.+\\.(ts|js|html)$': '@swc/jest', }, moduleFileExtensions: ['ts', 'html', 'js', 'json'], moduleNameMapper: { '@services/(.*)': '<rootDir>/src/app/services/$1', // 同步项目中所有路径别名配置 }, setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'], testEnvironment: 'jsdom', globals: { 'ts-jest': { skipBabel: true, }, }, };
- 用
@swc/jest替换ts-jest作为转换器 - 路径别名必须和项目tsconfig保持一致,避免模块解析错误
3. 校验 tsconfig.spec.json
确保测试专用TypeScript配置开启装饰器支持:
{ "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": ["jest", "node"], "emitDecoratorMetadata": true, "experimentalDecorators": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true }, "include": ["src/**/*.spec.ts", "src/**/*.d.ts"] }
experimentalDecorators和emitDecoratorMetadata是Angular编译的强制要求
4. 清理依赖冲突
检查package.json,移除ts-jest、babel-jest等冲突转换器,只保留必要依赖:
{ "devDependencies": { "@swc/jest": "^0.2.29", "jest": "^29.7.0", "jest-preset-angular": "^13.1.1", "@types/jest": "^29.5.11", "typescript": "~4.8.4" } }
验证步骤
- 删除
node_modules和锁文件(package-lock.json/yarn.lock),重新执行npm install - 清理Jest缓存:
npx jest --clearCache - 重新运行测试:
npx jest
内容的提问来源于stack exchange,提问作者Jan Pereira
相关产品推荐
相关产品推荐

