Sub topic 17
Testing infrastructure with assertions
This chapter assumes you can define a stack in TypeScript, know that cdk synth produces a CloudFormation template, and have used Jest or a similar test runner. You do not need an AWS account to run these tests.
Why test infrastructure
A CDK stack is ordinary code that produces a template. You can test that template before anything is deployed. A test catches a removed encryption setting or a missing permission in seconds, where a deployment takes minutes and can fail halfway.
The assertions module in aws-cdk-lib supports this. It synthesizes a stack in memory and gives you a Template object to inspect.
How a test runs
Nothing is sent to AWS. The test only reads the generated template.
A first test
The test below uses the AppStack from the earlier chapter. It checks the bucket's versioning and counts the Lambda functions.
import * as cdk from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import { AppStack } from '../lib/app-stack';
test('bucket is versioned and one function exists', () => {
const app = new cdk.App();
const stack = new AppStack(app, 'TestStack');
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::S3::Bucket', {
VersioningConfiguration: { Status: 'Enabled' },
});
template.resourceCountIs('AWS::Lambda::Function', 1);
});Run it with npx jest. A project created with cdk init app --language typescript already has Jest configured.
The main assertions
| Method | Use it to check |
|---|---|
| `hasResourceProperties(type, props)` | At least one resource of that type has matching properties |
| `resourceCountIs(type, n)` | Exactly `n` resources of that type exist |
| `hasResource(type, def)` | A resource matches, including attributes such as `DeletionPolicy` |
| `hasOutput(id, def)` | A stack output exists |
| `findResources(type)` | Returns matching resources for custom checks |
hasResourceProperties does a partial match. Properties you leave out are ignored, so a test stays valid when you add unrelated settings. Use Match.exact() when you need an exact structure. Use Match.objectLike(), Match.arrayWith() and Match.anyValue() to relax specific parts.
Testing a custom construct
You can test a construct such as SecureBucket by placing it in a throwaway stack. Check the settings it promises to apply:
import * as cdk from 'aws-cdk-lib';
import { Match, Template } from 'aws-cdk-lib/assertions';
import { SecureBucket } from '../lib/secure-bucket';
test('SecureBucket blocks public access and encrypts', () => {
const stack = new cdk.Stack();
new SecureBucket(stack, 'Test');
const template = Template.fromStack(stack);
template.hasResourceProperties('AWS::S3::Bucket', {
PublicAccessBlockConfiguration: Match.objectLike({
BlockPublicAcls: true,
}),
BucketEncryption: Match.anyValue(),
});
});Common errors
- Asserting on generated names. Logical IDs include a hash. Match on type and properties instead.
- Expecting resolved tokens. Values such as a bucket name appear as
ReforFn::GetAttobjects in the template. Assert on those objects, or useMatch.anyValue(). - Testing too much. Asserting the whole template makes tests fail on every harmless change. Test the behavior you care about, such as security settings.
- Bundling slowness. Stacks with Lambda assets can make tests slow because assets are staged during synthesis. Keep test fixtures small.
Exercise
A test calls template.hasResourceProperties('AWS::S3::Bucket', { VersioningConfiguration: { Status: 'Enabled' } }). You later add encryption: s3.BucketEncryption.S3_MANAGED to the bucket. Does the test still pass, and why?
Show answer
Yes. hasResourceProperties matches partially, so the extra BucketEncryption property is ignored. The test fails only if versioning is no longer enabled. To require an exact match, wrap the expected value in Match.exact().