typescript CDK Jest无法示例化类

x33g5p2x  于 2023-05-23  发布在  TypeScript
关注(0)|答案(1)|浏览(158)

我有一个像下面这样的类:

export class AbstractClass extends cdk.Stack {
    constructor(scope: Construct, id: string, props: SomeProps) {
        super(scope, id, props);
        ...
        ...
    }
}

另一个类是扩展上面的类:

export class MyLambdaStack extends AbstractClass {
    constructor(scope: Construct, id: string, props: SomeProps) {
        super(scope, id, props);
        ...
        ...
    }
}

我正在尝试编写MyLambdaStack类的单元测试。
这是单元测试(MyLambdaStack.test.ts):

describe("AskEC2 Health Monitor Lambda Stack", () => {
    const app = new App();
    const props: SomeProps = {...};
    const myLambdaStack = new MyLambdaStack(app, `test-id`, props);

    test("Placeholder test", () => {});
}

我一直在出错:

TypeError: MyLambdaStack_1.MyLambdaStack is not a constructor

我相信这个错误是由于课程被延长。如果我创建一个扩展cdk.Stack的AbstractClass示例,一切都可以正常工作。
知道怎么修吗?

o75abkj4

o75abkj41#

我不能复制你的错误。Stack继承模式在理论上没有什么不可行的,你的代码也没有任何明显的错误。
工作示例:

import { Construct } from "constructs";
import { App, Stack, StackProps, aws_lambda as lambda } from "aws-cdk-lib";
import { Template } from "aws-cdk-lib/assertions";

export class AbstractClass extends Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);
  }
}

export class MyLambdaStack extends AbstractClass {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    new lambda.Function(this, "Lambda", {
      code: new lambda.InlineCode(
        "exports.handler = async (event) => console.log(event)"
      ),
      runtime: lambda.Runtime.NODEJS_18_X,
      handler: "index.handler",
    });
  }
}

// ✅ passes
test("MyLambdaStack", () => {
  const app = new App();

  const stack = new MyLambdaStack(app, "MyTestStack", {
    env: { region: "us-east-1", account: "123456789012" },
  });

  const template = Template.fromStack(stack);

  template.resourcePropertiesCountIs("AWS::Lambda::Function", {}, 1);
});

请注意,如果目标是资源代码重用,CDK建议组合Construct子类而不是Stack继承:
当从多个AWS资源构建应用程序的高级逻辑单元时,请将每个逻辑单元表示为Construct,而不是Stack。通过使用构造进行构建,使用堆栈进行部署,您可以提高基础设施的重用潜力,并在如何部署基础设施方面给予更大的灵活性。

相关问题