AWS CDK 单元测试失败 - jest ts

时间:2021-01-25 03:34:01

标签: amazon-web-services jestjs amazon-iam aws-cdk

我在创建 IAM 角色的 Typescript 中创建了一个 AWS CDK 应用程序。这是我的代码:

export class AccountCreatorIamRoleStack extends cdk.Stack {
    public create(): iam.Role {
        const iamRole = some logic to create iam role goes here;
        return iamRole;
    }
}

我已经通过创建这样的 IAM 角色确认此代码有效:

var roleCreator = new AccountCreatorIamRoleStack(app, 'AccountCreatorIamRoleStack');
roleCreator.create();

但是,当我运行这个笑话单元测试时:

test('Test IAM Role Created', () => {
  const app = new cdk.App();
  // WHEN
  var stack = new AccountCreatorIamRoleStack(app, 'TestAccountCreatorIamRoleStack').create()
  // THEN
  expectCDK(stack).to(haveResource("AWS::IAM::Role"));
});

失败并出现以下错误:

 FAIL  test/account-creation-iam-role-stack.test.ts
  ✕ Test IAM Role Created (32 ms)

  ● Test IAM Role Created

    None of 0 resources matches resource 'AWS::IAM::Role' with {
      "$anything": true
    }.

      16 |   var stack = new AccountCreatorIamRoleStack(app, 'TestAccountCreatorIamRoleStack').create()
      17 |   // THEN
    > 18 |   expectCDK(stack).to(haveResource("AWS::IAM::Role"));
     |                    ^
      19 | });

      at HaveResourceAssertion.assertOrThrow (node_modules/@aws-cdk/assert/lib/assertions/have-resource.ts:100:13)
      at StackInspector._to (node_modules/@aws-cdk/assert/lib/inspector.ts:25:15)
      at StackInspector.to (node_modules/@aws-cdk/assert/lib/inspector.ts:15:14)
      at Object.<anonymous> (test/account-creation-iam-role-stack.test.ts:18:20)

我可以看到它指向该行上的某些内容,但它认为是错误的究竟指向了什么?想法?

2 个答案:

答案 0 :(得分:0)

您的代码断言 AWS::IAM::Role 具有 "VisibilityTimeout": 300 但它没有这样的属性。当您的代码实际创建它时,它应该单独传递 haveResource("AWS::IAM::Role")(没有附加属性)。

以下是 IAM 角色的当前属性:https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html

{
  "Type" : "AWS::IAM::Role",
  "Properties" : {
      "AssumeRolePolicyDocument" : Json,
      "Description" : String,
      "ManagedPolicyArns" : [ String, ... ],
      "MaxSessionDuration" : Integer,
      "Path" : String,
      "PermissionsBoundary" : String,
      "Policies" : [ Policy, ... ],
      "RoleName" : String,
      "Tags" : [ Tag, ... ]
    }
}```

答案 1 :(得分:0)

在尝试确定资源是否已创建时,您应该使用的是 countResources

expectCDK(stack).to(countResources('AWS::IAM::Role', 1));

当使用 haveResource 时,它希望有一个对象与之进行比较。由于您没有提供要比较的对象,因此这将失败。此外,如果您不检查对象期望值,则此检查毫无意义,而应改用 countResources

这是使用 haveResource 进行对象期望的示例:

test('Verify IAM AssumeRole', () => {
  expectCDK(stack).to(
    haveResource('AWS::IAM::Role', {
      AssumeRolePolicyDocument: {
        Statement: [
          {
            Action: 'sts:AssumeRole',
            Effect: 'Allow',
            Principal: {
              Service: [
                'codestar.amazonaws.com',
              ],
            },
          },
        ],
      },
      RoleName: 'some-name-for-assume-role',
    }),
  );
});

您还拥有 haveResourceLike,它可以对部分乐曲有所帮助,或者您甚至可以使用 arrayWith(objectLike({...}))

一个例子:

// ECR Auth token Access
expectCDK(stack).to(
  haveResourceLike('AWS::IAM::Policy', {
    PolicyDocument: {
      Statement: arrayWith(
        objectLike({
          Action: 'ecr:GetAuthorizationToken',
          Effect: 'Allow',
          Resource: '*',
        }),
      ),
    },
  }),
);

至于它指向 stack 的问题,这是因为堆栈没有与您期望的匹配的资源。它指向堆栈,因为这是正在测试的内容,它在那里(有点误导)表明 stack 可能是问题所在。尽管您的问题似乎只是您使用了错误的测试方法。

此外,错误消息需要一些工作。它们真的没有那么有用,而且很多都是误导性的。我遇到过无数次:

<块引用>

TypeError:将循环结构转换为 JSON

当使用对象期望时。通常这是因为一个值不匹配但错误完全没有用......我无法计算这让我头疼多少次......

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