unit-testingjestjsaws-cdk

In CDK testing, what is the difference between toHaveResource and toHaveResourceLike?


In CDK fine-grained construct tests, what is the different between

expect(...).toHaveResource(...)

and

expect(...).toHaveResourceLike(...)

from the @aws-cdk/assert/jest module?


Solution

  • According to the code here and here the only difference is that toHaveResource requires that values for the keys passed must match exactly, while in toHaveResourceLike actual values can be a superset of reference values. In other words, if you are trying to assert value of some property, which itself is an object, and you want to assert only subset of the object, then you should use toHaveResourceLike.

    For example, let's say that you're trying to assert that your S3 bucket resource has a PublicAccessBlockConfiguration property with BlockPublicPolicy set to true.

    You might write something like this:

    test("has public access restricted", () => {
      expect(stack).toHaveResource("AWS::S3::Bucket", {
        PublicAccessBlockConfiguration: {
          BlockPublicPolicy: true,
        },
      });
    });
    

    But this will fail because PublicAccessBlockConfiguration also has other subproperties like BlockPublicAcls. But if you switch toHaveResource here to toHaveResourceLike then it will succeed.