How do you mock an existing vpc in aws-cdk unit tests?

Viewed 2476

I am writing an AWS CDK application that creates a ECS Fargate stack. It uses an existing VPC and existing ECR repositories. Simply mocking my Interface, and returning mocks of the IVpc and IRepository interfaces gets me past initial problems, but when the CDK goes to use those constructs, I get more errors.

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

I get this error:

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

This seems like a possible "black hole" where I will need to understand every usage of the mock and account for it. I'm looking for a better way to consistently model my existing resources so that I can test my new code. Any advice would be appreciated.

1 Answers

For anyone that comes across this question, I decided to construct a VPC with known parameters for purposes of my tests. This VPC is returned from the mock fromLookup function.

For example: to build the 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
  });
}

And then to use the vpc in the mock of my ExistingResources class,

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>();
    }
  }
);

This allows me to do snapshot testing in a disconnected environment.

Related