1

I am trying to do some snapshot testing on my CDK stack but the snapshot is not generating.

This is my stack:

export interface SNSStackProps extends cdk.StackProps {
  assumedRole: string
}

export class SNSStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props: AssumedRole) {
    super(scope, id, props)

    const topicName = "TopicName"

    const topic = new sns.Topic(this, topicName, {
      displayName: "Topic Name",
      fifo: true,
      topicName: topicName,
      contentBasedDeduplication: true
    })

    const assumedRole = iam.Role.fromRoleArn(
      this,
      "AssumedRole",
      props.assumedRole
    )

    topic.grantPublish(assumedRole.grantPrincipal)
  }
}

This is my snapshot test

test("Creates an SNS topic ", () => {
  const stack = new Stack()
  new SNSStack.SNSStack(stack, "SNSStack", {
    env: {
      account: "test_account",
      region: "test_region"
    },
    assumedRoleArn: "arn:aws:iam::1111111:role/testRole"
  })
  expect(SynthUtils.toCloudFormation(stack)).toMatchSnapshot()
})

This generates a snapshot with an empty object like this

exports[`dlq creates an alarm 1`] = `Object {}`;

Why is the object empty in the snapshot? And how do I get the Object in the snapshot to populate with the resources in my stack?

DrkStr
  • 1,752
  • 5
  • 38
  • 90
  • I think the snapshot you shared is not related to the test you shared since they have different names. I think it's useful to name the snapshot too. `.toMatchSnapshot('your snapshot name here')` – Violeta Aug 13 '21 at 17:21

1 Answers1

0

You should create a Stack by using an App and not another stack. You can then easily synthesize the App and extract the JSON cloudformation stack which you can use for your snapshot. Below is an example of how I've used it to create the stack and retrieve the CloudFormation.

const app = new App();
new ApiStack(app, 'api-stack', params);
return app.synth({ force: true }).getStackByName('api-stack').template;

It is possible that once you've got the stack reference, you can use the SynthUtils way to get the CloudFormation repository.

stijndepestel
  • 3,076
  • 2
  • 18
  • 22