jestjsaws-cdk

AWS CDK Jest Unit Test Resource Has DeletionPolicy


In the AWS CDK, I can write a Jest unit test to test if a resource has a specific property. But how do I test a resource DeletionPolicy value which is NOT a property?

cdk.out/example.template.json (simplified)

"AppsUserPool8FD9D0C0": {
  "Type": "AWS::Cognito::UserPool",
  "Properties": {
    "UserPoolName": "test",
    ...
  },
  "UpdateReplacePolicy": "Retain",
  "DeletionPolicy": "Retain",
  "Metadata": {}
}

Jest unit test passes for property (simplified)

expect(stack).toHaveResourceLike('AWS::Cognito::UserPool', {
  "UserPoolName": "test"
});

Jest unit test fails for DeletionPolicy (simplified)

expect(stack).toHaveResourceLike('AWS::Cognito::UserPool', {
  "DeletionPolicy": "Retain"
});

Solution

  • You can use the following example https://github.com/aws/aws-cdk/blob/775a0c930a680f8a52bb4a40084d07492f7f9fee/packages/%40aws-cdk/aws-cloudformation/test/test.resource.ts#L57

    You can use haveResouce() with parameter ResourcePart.CompleteDefinition

    snippet from the example

          expect(stack).to(haveResource('AWS::CloudFormation::CustomResource', {
            DeletionPolicy: 'Retain',
            UpdateReplacePolicy: 'Retain',
          }, ResourcePart.CompleteDefinition));