question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[assert] SynthUtils.toCloudFormation(stack)).toMatchSnapshot will fail with CDK Pipelines because the output changes every time

See original GitHub issue

❓ General Issue

Consider the following code where PipelineStack is a stack containing CDK Pipelines and some infra code.

  const app = new cdk.App({
    context: {
      '@aws-cdk/core:newStyleStackSynthesis': 'true',
    },
  });
  const stack = new PipelineStack(app, 'PipelineStack', [], {
    env: {
      region: 'eu-central-1',
    },
  });
  // THEN
  expect(SynthUtils.toCloudFormation(stack)).toMatchSnapshot();

Running the test will fail because the output changes every time:

  ● PipelineStack

    expect(received).toMatchSnapshot()

    Snapshot name: `PipelineStack 1`

    - Snapshot  - 1
    + Received  + 1

    @@ -738,11 +738,11 @@
              \"git init && npx cdk synth\"
            ]
          }
        },
        \"artifacts\": {
    -     \"base-directory\": \"var/folders/5f/y0wjdf0122sgz4vvyt4l0h080000gn/T/cdk.outgD8H3Y\",
    +     \"base-directory\": \"var/folders/5f/y0wjdf0122sgz4vvyt4l0h080000gn/T/cdk.outfqommz\",
          \"files\": \"**/*\"
        }
      }",
                "Type": "CODEPIPELINE",
              },

The Question

Is this a bug in how CDK builds the project or would it be possible to somehow ignore changes in certain properties that are unrelated to the test? What is the recommended approach here?

Environment

  • CDK CLI Version: 1.62.0 (build 8c2d7fc)
  • Module Version: 1.62.0
  • Node.js Version: v14.8.0
  • OS: macOs
  • Language (Version): TypeScript 4

Other information

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:6
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

4reactions
straygarcommented, Oct 26, 2020

Not a solution, but a workaround is to use a custom snapshot serializer to omit these paths (note - the replacement might a bit agressive, but will at least avoid false-positives):

/** 
 * A custom snapshot serializer, used to remove any randomly generated hash values, that would lead to false positives in snapshot tests.
*/
expect.addSnapshotSerializer({
    test: template => typeof template === 'string',
    print: template => {
        const sanitizedTemplate = (template as string)
            .replace(/\"base-directory\": \".+\"/, '"base-directory": "[HASH REMOVED]"')
            .replace(/\"value\":\"[a-z0-9]+\"/, '"value": "[HASH REMOVED]"');
        return `"${sanitizedTemplate}"`;
    },
});
2reactions
markuslcommented, Feb 26, 2021

Just adding a comment for future readers:

In addition to setting the outdir you likely want to turn off the stack traces from the test output:


test('ExampleEcsClusterStack should synthesize to expected snapshot', () => {
  const app = new cdk.App( { 
    outdir: 'cdk.out',
    stackTraces: false,
  });
  // WHEN
  const stack = new ExampleEcsClusterStack(app, 'ecs-stack', { ...props });

  // THEN
  const snapshot = SynthUtils.synthesize(stack);

  expect(snapshot).toMatchSnapshot();
});


Read more comments on GitHub >

github_iconTop Results From Across the Web

Testing constructs - AWS Cloud Development Kit (AWS CDK) v2
Fine-grained assertions test specific aspects of the generated AWS CloudFormation template, such as "this resource has this property with this value." These ...
Read more >
CDK Upgrade: cannot find equivalent to "expect(SynthUtils ...
Hi it's not available in aws-cdk version 2, you can use toJSON instead from the Template class. For code example please refer to...
Read more >
CDK Integration Testing | Ben's Blog
Learn how to run integration tests as part of a stack deployment, and automatically roll-back changes when things don't go right.
Read more >
Infrastructure Tests with CDK - kreuzwerker
This article gives an overview of the main testing functionalities provided by the AWS Cloud Development Kit (CDK) and shares some of our ......
Read more >
CDK V2 Snapshot Testing with assertions (alpha lib)
With CDK V1 and CDK V2 the testing libraries created a little bit of confusion - at least on my side :) ....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found