Writing Unit Tests for the CDK

Modeling the infrastructure is straight forward. Now let’s do some TDD. Let’s create a new folder and start by wring some tests, then adding the code.

Setup the test directory and files

Create a new project.

In the root of the new project create a directory test. In the test directory create a new file that ends in -test.ts.

mkdir create-vpc-tdd
cdk init --language typescript
mkdir test
touch test/create-vpc-tdd-test.ts

The convention is to use the file name you are testing <filename>-test.ts.

The modules we will use are nodeunit and @aws-cdk/assert, so install them.


npm i @aws-cdk/assert
npm i @types/nodeunit

Open the test file and add the following to the top of the file.

import cdk = require('@aws-cdk/cdk');
import { expect, haveResource } from '@aws-cdk/assert';
import { CreateVpcTddStack } from '../lib/create-vpc-tdd-stack';
import { Test } from 'nodeunit';

Open AWS CDK github repo and navigate to an example testing creating a VPC.

What do we want to test? let’s make sure the VPC has DNS support

What do you notice about the pattern for writing tests?

export = {
  "When creating a VPC": {
    "with the default CIDR range": {
      'vpc has CidrBlock and DNS Support'(test: Test) {
        const app = new cdk.App();
    
        const stack = new CreateVpcTddStack(app, 'CreateVpcTddStack');
    
        expect(stack).to(haveResource('AWS::EC2::VPC', {
          CidrBlock: '10.0.0.0/16',
          EnableDnsSupport: true,
          EnableDnsHostnames: true
        }));
    
        test.done();
      }
    }
  }
}

Let’s automate some cruft. Open the package.json and add the line:

"test": "tsc; nodeunit test/<filename>-test.js" to the scripts key of the package.json file.

Run npm run test

Now write the VPC code to make the test pass.

Prev :: Next

Resources

  1. AWS CDK github repo
  2. AWS CDK Documentation
  3. AWS CloudFormation Template Reference