I've created an S3 bucket using the AWS CDK like so
new s3.Bucket(this, 'MyFirstBucket', {
versioned: true,
encryption: s3.BucketEncryption.KMS,
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
});
But I'm not having much success writing Jest tests for it. I've tried to follow https://docs.aws.amazon.com/cdk/v2/guide/testing.html#Capturing but not really having anyluck. The s3.BlockPublicAccess.BLOCK_ALL returns
{"blockPublicAccess": {"blockPublicAcls": true, "blockPublicPolicy": true, "ignorePublicAcls": true, "restrictPublicBuckets": true}}
but when I try to compare this in my tests the object is comprised of
..."PublicAccessBlockConfiguration": {"BlockPublicAcls": true, "BlockPublicPolicy": true, "IgnorePublicAcls": true, "RestrictPublicBuckets": true}...
I've managed to pass tests but only by copying content from the CDK.out json file, however I feel this is counterintuitive to how tests should be written. Below is my Test code, Any help would be much appreciated.
expect(template).toHaveProperty("AWS::S3::Bucket", {
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL
}) ```
CodePudding user response:
This is the expected behavior. The fine-grain assertions "test specific aspects of the generated AWS CloudFormation template". Templates have PascalCase property keys. So we can't assert against the camelCase keys in the Typescript CDK classes.
Not a problem! Simply convert the camelCase to PascalCase:
const blockAllAccess = s3.BlockPublicAccess.BLOCK_ALL as unknown as Record<string, string>;
const blockAllAccessPascal = Object.entries(blockAllAccess).reduce(
(acc, [k, v]) => {
acc[k[0].toUpperCase() k.substring(1)] = v;
return acc;
}, {});
expect(bucketStack).toHaveResourceLike('AWS::S3::Bucket', {
PublicAccessBlockConfiguration: blockAllAccessPascal,
});
