首页 > 解决方案 > 您如何在 aws-cdk 单元测试中模拟现有的 vpc?

问题描述

我正在编写一个创建 ECS Fargate 堆栈的 AWS CDK 应用程序。它使用现有的 VPC 和现有的 ECR 存储库。简单地模拟我的接口,并返回 IVpc 和 IRepository 接口的模拟,就可以解决最初的问题,但是当 CDK 开始使用这些构造时,我会遇到更多错误。

    const mockResources = mock<IExistingResources>(
      {
        getVpc: (scope: cdk.Construct, vpcId: string) => {
          return mock<IVpc>();
        },
    
        getElasticContainerRepository: (scope: cdk.Construct, id: string, repositoryName: string) => {
          return mock<IRepository>();
        }
      }
    );

我收到此错误:

TypeError: Cannot destructure property 'subnetIds' of 'baseProps.vpc.selectSubnets(...)' as it is undefined.

这似乎是一个可能的“黑洞”,我需要了解模拟的每一种用法并对其进行解释。我正在寻找一种更好的方法来一致地对现有资源进行建模,以便我可以测试我的新代码。任何意见,将不胜感激。

标签: unit-testingamazon-ec2aws-cdk

解决方案


对于遇到此问题的任何人,我决定构建一个具有已知参数的 VPC 以进行测试。此 VPC 是从模拟fromLookup函数返回的。

例如:构建 VPC

function buildVpc(scope: cdk.Construct, vpcId:string): IVpc {
  return new Vpc(scope, vpcId, {
    cidr: '10.0.0.0/16',
    maxAzs: 2,
    subnetConfiguration: [{
      cidrMask: 26,
      name: 'isolatedSubnet',
      subnetType: SubnetType.PUBLIC,
    }],
    natGateways: 0
  });
}

然后在我ExistingResources班级的模拟中使用vpc,

const mockResources = mock<IExistingResources>(
  {
    getVpc: (scope: cdk.Construct, vpcId: string) => {
      return buildVpc(scope, vpcId);
    },

    getElasticContainerRepository: (scope: cdk.Construct, id: string, repositoryName: string) => {
      return mock<IRepository>();
    }
  }
);

这允许我在断开连接的环境中进行快照测试。


推荐阅读