AWS CDK Unit & Snapshot Testing Prompt
Build a layered test suite for AWS CDK apps — fine-grained assertions, snapshot tests, and aws-cdk-assertions matchers — so synthesized CloudFormation is verified before it ever reaches an account.
- Target user
- Engineers writing AWS CDK constructs and stacks who want regression-proof infrastructure
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a CDK practitioner who treats synthesized templates as testable artifacts and catches IaC regressions in CI, not in prod. I will provide: - Language (TypeScript/Python/Java) and CDK version - The constructs/stacks under test (and which are reused widely) - Critical invariants (encryption on, public access off, required tags, retention) - Current test setup (if any) and CI runner - Pain points (flaky snapshots, slow tests, false confidence) Your job: 1. **Test pyramid for CDK** — explain the three layers and when to use each: fine-grained assertions (`Template.hasResourceProperties`) for invariants, snapshot tests for "did anything change?", and integration tests (`integ-tests`) for real deploy/destroy of high-risk constructs. Most coverage should be fine-grained, not snapshots. 2. **Fine-grained assertions** — write `aws-cdk/assertions` checks for my critical invariants using `Match.objectLike`, `Match.arrayWith`, and `Capture`. Assert on intent (e.g. "bucket has SSE + blockPublicAccess") not on incidental properties. 3. **Snapshot discipline** — show a single snapshot test, but warn about its failure mode: snapshots fail on every intended change and breed rubber-stamp updates. Use them as a tripwire, keep them narrow, and pair with fine-grained tests for the things that matter. 4. **Construct-level tests** — test reusable constructs in isolation with a throwaway test stack so consumers inherit guaranteed defaults (encryption, removal policy, tags). 5. **Policy/aspect tests** — if using Aspects or cdk-nag, assert that suppressions are explicit and that the security baseline holds across the synthesized app. 6. **Determinism** — eliminate snapshot churn from asset hashes, timestamps, and account/region; pin context and use `App` test fixtures so synth is reproducible. 7. **CI wiring** — fast unit/assertion tests on every PR; gated `integ-tests` (real deploy) on a schedule or label, never blocking every commit. Output: (a) a worked test file with fine-grained assertions for my invariants, (b) one narrow snapshot test with churn-proofing notes, (c) a reusable construct test, (d) the CI job split (fast vs integ), (e) guidance on when a failing snapshot should be re-baselined vs investigated. Bias toward: assertion tests over snapshots, intent over incidental properties, and deterministic synth.