You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest单元测试中装饰器的design:paramtypes获取为空问题

解决Jest测试中Reflect.getMetadata("design:paramtypes")返回空的问题

核心原因

design:paramtypes元数据由TypeScript编译器生成,依赖两个关键编译配置:

  • 启用experimentalDecorators以支持装饰器语法
  • 启用emitDecoratorMetadata让编译器自动生成参数类型元数据

同时在Jest环境中,需确保ts-jest正确读取这些配置,且reflect-metadata在装饰器解析前完成导入。

解决方案步骤

1. 配置TypeScript编译选项

修改tsconfig.json,确保以下选项开启:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "ES6", // 需指定ES6及以上版本以支持装饰器特性
    // 其他编译选项...
  }
}

2. 让ts-jest加载正确的tsconfig

在Jest配置文件中,显式指定ts-jest使用你的tsconfig.json,避免默认配置覆盖关键选项:

module.exports = {
  roots: ['<rootDir>'],
  testMatch: [
    "<rootDir>/tests/**/*.+(ts|tsx|js)",
    "**/?(*.)+(_spec|_test).+(ts|tsx|js)"
  ],
  transform: {
    "^.+\\.(ts|tsx)$": ["ts-jest", {
      tsconfig: "tsconfig.json"
    }]
  },
  setupFiles: [ // 改用setupFiles确保在测试文件加载前导入reflect-metadata
    '<rootDir>/src/jest/StandardLogger.ts',
    '<rootDir>/src/jest/startup.ts'
  ],
  verbose: true,
  testURL: "http://localhost/"
} 

注意:将setupFilesAfterEnv替换为setupFiles,因为setupFiles会在测试文件加载前执行,保证reflect-metadata在装饰器解析前完成导入。

3. 验证类的构造函数参数

如果类没有构造函数参数,Reflect.getMetadata("design:paramtypes", target)返回空数组是正常行为。例如你提供的测试代码中SomeClass无构造参数,输出空数组符合预期。若实际业务类有构造参数,测试时需确保类定义包含这些参数:

class Dependency {}

@someDecorator()
export class SomeClass {
  constructor(private dep: Dependency) {} // 存在构造参数时才会生成非空的paramtypes数组
  invoke() {
    console.log('hello');
  }
}

验证测试

修改配置后重新运行测试,若类包含构造函数参数,Reflect.getMetadata("design:paramtypes", target)应返回对应的参数类型数组。

内容的提问来源于stack exchange,提问作者jgauffin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:10:43