AWS CDK 为对象属性的 Jest 测试提供了不正确的定义

AWS CDK providing incorrect definitions for Jest testing on object properties

我已经像这样使用 AWS CDK 创建了一个 S3 存储桶

new s3.Bucket(this, 'MyFirstBucket', {
      versioned: true,
      encryption: s3.BucketEncryption.KMS,
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
    });

但是我为它编写 Jest 测试并没有取得多大成功。我试过关注 https://docs.aws.amazon.com/cdk/v2/guide/testing.html#Capturing 但运气不佳。 s3.BlockPublicAccess.BLOCK_ALL returns {"blockPublicAccess": {"blockPublicAcls": true, "blockPublicPolicy": true, "ignorePublicAcls": true, "restrictPublicBuckets": true}}

但是当我尝试在我的测试中比较它时,该对象由

组成

..."PublicAccessBlockConfiguration": {"BlockPublicAcls": true, "BlockPublicPolicy": true, "IgnorePublicAcls": true, "RestrictPublicBuckets": true}...

我已经设法通过了测试,但只是从 CDK.out json 文件中复制了内容,但是我觉得这与编写测试的方式有悖常理。下面是我的测试代码,任何帮助将不胜感激。

  expect(template).toHaveProperty("AWS::S3::Bucket", {
        blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL
    }) ```

这是预期的行为。 fine-grain assertions “测试生成的 AWS CloudFormation 模板的特定方面”。模板有 PascalCase 属性 键。所以我们不能针对 Typescript CDK 类.

中的 camelCase 键进行断言

没问题!只需将 camelCase 转换为 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,
});