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

Jest测试AWS CDK报错Class constructor Stack cannot be invoked without 'new'如何解决

问题根因

你遇到的Class constructor Stack cannot be invoked without 'new'报错,是因为aws-cdk/core包导出的Stack为ES6+规范实现的原生类,你当前的编译配置将自身编写的TypeScript代码转译为ES5规范的构造函数,ES5构造函数调用原生ES6类时就会触发该报错。单独实例化cdk.App未报错只是该类的实现恰好兼容ES5调用,不代表配置没有问题。

解决方案

按优先级依次尝试以下操作即可解决:

  • 调整tsconfig编译配置
    修改项目根目录下tsconfig.json的compilerOptions配置,将编译目标调整为ES2020及以上版本,同时新增esModuleInterop配置保证模块导入兼容:
    {
      "compilerOptions": {
        "target": "ES2020",
        "esModuleInterop": true,
        // 其余原有配置保持不变
      }
    }
    
  • 明确指定ts-jest使用项目tsconfig
    若调整完tsconfig后仍报错,修改jest.config.json的transform配置,明确告知ts-jest使用项目的tsconfig文件进行编译:
    module.exports = {
      testEnvironment: 'node',
      roots: ['<rootDir>/test'],
      testMatch: ['**/*.test.ts'],
      transform: {
        '^.+\\.tsx?$': [
          'ts-jest',
          {
            tsconfig: '<rootDir>/tsconfig.json'
          }
        ]
      }
    };
    
  • 修正代码语法错误
    你贴出的KmsMultiregionPrincipalKey类定义末尾多了一个多余的闭合花括号,需要删除避免编译异常:
    export class KmsMultiregionPrincipalKey extends cdk.Stack {
      public readonly principalKeyArn: string;
    
      constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
        // 剩余类逻辑代码在此处
      }
    }
    

完成以上修改后重新执行测试即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:24:03