DEV Community

Cover image for CDK V2 Snapshot Testing with assertions (alpha lib)
Gernot Glawe for AWS Community Builders

Posted on

CDK V2 Snapshot Testing with assertions (alpha lib)

With CDK V1 and CDK V2 the testing libraries created a little bit of confusion - at least on my side :) . What to import and how to test.

So I just wanted to share a snapshot code snippet in Typescript to use a snapshot test in CDK V2.

Assume you have a "user" stack, which you want to refactor. So, make a snapshot test:

import { Template } from "@aws-cdk/assertions-alpha";
import * as cdk from 'aws-cdk-lib';
import { User } from '../lib/user';


describe("User", () => {
    test("snapshot after refactor", () => {
        const stack = new cdk.Stack();

        const env = {
            account: '5555555555',
            region: "eu-central-1"
        }
        const user = new User(stack, "user", { env })
        const template = Template.fromStack(user);
        expect(template).toMatchSnapshot();


    });
});
Enter fullscreen mode Exit fullscreen mode

If you have a file, e.g. "user.test.ts" in your "/test" subdirectory, the first npm run test will create a snapshot in test/__snapshots__/.

First time you see:

 PASS  test/user.test.ts
  user
    ✓ snapshot after refactor (288 ms)

 › 1 snapshot written.
Snapshot Summary
 › 1 snapshot written from 1 test suite.

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 written, 1 total
Time:        4.698 s, estimated 6 s
Ran all test suites.
Enter fullscreen mode Exit fullscreen mode

If you now change anything and a different CloudFormation Template is generated you will notice.

I just changed one username from "gernot" to "gernot2" and npm run test gives:

...
          ],
    -         "UserName": "gernot",
    +         "UserName": "gernot2",
Enter fullscreen mode Exit fullscreen mode

When is this useful?

If you refactor code like creating a base Construct/Object.
At first, you dont`t want to change any functionality.

This snapshot test will prove that.

Happy CDK-ing!

Thanks for a nice picture:

Photo by Marco Bianchetti on Unsplash

Top comments (0)