我正在编写一个创建 ECS Fargate 堆栈的 AWS CDK 应用程序。它使用现有的 VPC 和现有的 ECR 存储库。简单地模拟我的接口(interface),并返回 IVpc 和 IRepository 接口(interface)的模拟让我解决了最初的问题,但是当 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.
这似乎是一个可能的“黑洞”,我需要了解模拟的每一种用法并对其进行解释。我正在寻找一种更好的方法来一致地对我现有的资源进行建模,以便我可以测试我的新代码。任何建议将不胜感激。
最佳答案
对于遇到这个问题的任何人,我决定构建一个具有已知参数的 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
类的 mock 中使用 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>();
}
}
);
这让我可以在断开连接的环境中进行快照测试。
关于unit-testing - 您如何在 aws-cdk 单元测试中模拟现有的 vpc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63191913/