How do we do Unit testing for AWS CDK code? And should we?

aws-cdk has a library of testing utilities that are useful for asserting against stacks. The cdk repo uses it itself for a lot of its own unit tests.

https://www.npmjs.com/package/@aws-cdk/assert

This allows you to do something like

// jest
test('configurable retention period cannot exceed 14 days', () => {
  const stack = new MyStack();
  expect(stack).to(haveResource('AWS::SomeService::SomeResource', {
    SomePropertyOnResource: 'some-value-it-should-have'
  }));
});

This is only supported for CDK apps written in typescript as of now, but the plan is to eventually support all languages cdk supports.

Whether or not you should do this usually is similar to asking whether you should unit test any codebase. If you have a lot of complex business logic happening that does things like conditionally creating resources or otherwise changing your apps behavior, its probably worth getting some coverage in those places. If your app is essentially a bunch of static declarations without conditionals, loops, etc, maybe you can get by with just running cdk diff when making changes and manually verifying your expected changes.

If you're writing custom constructs for reusing in different cdk apps, unit testing those is probably a good idea.

Some relevant docs https://docs.aws.amazon.com/cdk/latest/guide/testing.html