CDK Unit Tests using Jest and GitHub Actions

Simple Test for CDK Stack looks so such

import * as cdk from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import * as InfrastructureAsCode from '../lib/infrastructure_as_code-stack';

// example test. To run these tests, uncomment this file along with the
// example resource in lib/infrastructure_as_code-stack.ts
test('SQS Queue Created', () => {
    const app = new cdk.App();
    // WHEN
    const stack = new InfrastructureAsCode.InfrastructureAsCodeStack( app, 'MyTestStack' );
    
    // THEN
    const template = Template.fromStack( stack );
    
    template.hasResourceProperties( 'AWS::SQS::Queue', {
        VisibilityTimeout: 300
    });
});

But for Cloud Developement is good to use snapshots for tests. Use 'jest-cdk-snapshot'::

Install jest-cdk-snapshot

yarn add jest-cdk-snapshot -D

Then use it Tests. The Previous Test should looks so such:

import * as cdk from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import * as InfrastructureAsCode from '../lib/infrastructure_as_code-stack';
import 'jest-cdk-snapshot';

// example test. To run these tests, uncomment this file along with the
// example resource in lib/infrastructure_as_code-stack.ts
test('SQS Queue Created', () => {
    const app = new cdk.App();
    // WHEN
    const stack = new InfrastructureAsCode.InfrastructureAsCodeStack( app, 'MyTestStack' );
    
    expect( stack ).toMatchCdkSnapshot();
    
    // THEN
    const template = Template.fromStack( stack );
    
    template.hasResourceProperties( 'AWS::SQS::Queue', {
        VisibilityTimeout: 300
    });
});

Now when run `yarn run test` you will recieve errors:

Snapshot Summary
 › 1 snapshot failed from 1 test suite. Inspect your code changes or run `yarn test -u` to update them.

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   1 failed, 1 total

If you want to update snapshot with new code changes run tests with '-u' option

yarn run test -- -u

 

0 ( 0 ) Comments