如何为含装饰器的TypeScript项目配置Jest测试编译后的Build代码
测试TypeScript编译后代码时的装饰器语法错误解决
我有一个使用装饰器的TypeScript项目,编译输出目录为build。我想直接测试编译后的代码而非源码,因此测试路径指向build目录,原本以为不需要用ts-jest。但运行Jest测试时出现错误:
SyntaxError: /.../models/externalEntity.model.ts: Support for the experimental syntax 'decorators' isn't currently enabled (6:1)
我尝试配置babel-jest转换规则如下,但还是出现其他装饰器相关错误:
transform: { "\\.(js|jsx|ts|tsx)$": [ "babel-jest", { decoratorsBeforeExport: true, plugins: [ "@babel/plugin-proposal-decorators", "@babel/plugin-syntax-decorators", ], }, ], },
我的Jest配置和tsconfig配置如下:
当前Jest配置
module.exports = { testEnvironment: "node", rootDir: "./build", testMatch: ['<rootDir>/**/integration/?(*.)+(spec|test).[jt]s?(x)'] }
当前tsconfig配置
{ "include": ["./src/**/*"], "exclude": [], "compilerOptions": { "incremental": true, "target": "es2019", "module": "commonjs", "lib": ["es2019", "esnext.asynciterable"], "allowJs": true, "checkJs": false, "outDir": "build", "rootDir": "src", "noImplicitAny": false, "strictNullChecks": false, "strictFunctionTypes": false, "strictBindCallApply": false, "noImplicitThis": false, "noUnusedLocals": true, "moduleResolution": "node", "baseUrl": "./", "allowSyntheticDefaultImports": true, "esModuleInterop": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "preserveConstEnums": true, "resolveJsonModule": true, "traceResolution": false, "extendedDiagnostics": false }, }
解决步骤
1. 修正babel-jest装饰器配置
TypeScript使用的是旧版装饰器提案,你的babel插件配置顺序和参数有误。去掉重复的语法插件,指定legacy: true参数,修改后的transform配置如下:
transform: { "^.+\\.js$": [ "babel-jest", { plugins: [ ["@babel/plugin-proposal-decorators", { legacy: true }] ] } ] }
注:只需要处理编译后的JS文件,无需匹配TS/TSX后缀。
2. 调整Jest配置范围
确保Jest只处理build目录下的文件,避免误触源码:
module.exports = { testEnvironment: "node", rootDir: "./build", testMatch: ['<rootDir>/**/integration/?(*.)+(spec|test).js'], testPathIgnorePatterns: ['/src/'], transform: { "^.+\\.js$": [ "babel-jest", { plugins: [["@babel/plugin-proposal-decorators", { legacy: true }]] } ] } }
3. 安装必要依赖
确保已安装所需的babel包:
npm install --save-dev @babel/core @babel/jest @babel/plugin-proposal-decorators
4. 验证编译结果
检查build目录下的JS文件,确认装饰器已被编译为__decorate这类辅助函数(TypeScript开启experimentalDecorators后会自动生成)。
内容的提问来源于stack exchange,提问作者Ofek Israel
相关产品推荐
相关产品推荐

