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