diff --git a/packages/aws-cdk-lib/assertions/lib/template.ts b/packages/aws-cdk-lib/assertions/lib/template.ts index b85b718c15f42..6dc609301291c 100644 --- a/packages/aws-cdk-lib/assertions/lib/template.ts +++ b/packages/aws-cdk-lib/assertions/lib/template.ts @@ -296,12 +296,12 @@ export interface TemplateParsingOptions { } function toTemplate(stack: Stack): any { - const root = stack.node.root; - if (!Stage.isStage(root)) { + const stage = Stage.of(stack); + if (!Stage.isStage(stage)) { throw new Error('unexpected: all stacks must be part of a Stage or an App'); } - const assembly = root.synth(); + const assembly = stage.synth(); if (stack.nestedStackParent) { // if this is a nested stack (it has a parent), then just read the template as a string return JSON.parse(fs.readFileSync(path.join(assembly.directory, stack.templateFile)).toString('utf-8')); diff --git a/packages/aws-cdk-lib/assertions/test/template.test.ts b/packages/aws-cdk-lib/assertions/test/template.test.ts index 2deb97c1e2197..eaced11409952 100644 --- a/packages/aws-cdk-lib/assertions/test/template.test.ts +++ b/packages/aws-cdk-lib/assertions/test/template.test.ts @@ -1,4 +1,16 @@ -import { App, CfnCondition, CfnMapping, CfnOutput, CfnParameter, CfnResource, Fn, LegacyStackSynthesizer, NestedStack, Stack } from '../../core'; +import { + App, + CfnCondition, + CfnMapping, + CfnOutput, + CfnParameter, + CfnResource, + Fn, + LegacyStackSynthesizer, + NestedStack, + Stack, + Stage +} from '../../core'; import { Construct } from 'constructs'; import { Capture, Match, Template } from '../lib'; @@ -1353,6 +1365,29 @@ describe('Template', () => { }); }).not.toThrow(/dependency cycle/); }); + + test('nested stack inside a Stage in an App', () => { + const app = new App(); + const stage = new Stage(app, 'Stage'); + const stack = new Stack(stage); + const nested = new NestedStack(stack, 'MyNestedStack'); + new CfnResource(nested, 'Bar', { + type: 'Bar::Baz', + properties: { + Qux: 'Foo', + }, + }); + const template = Template.fromStack(nested); + + expect(template.toJSON()).toEqual({ + Resources: { + Bar: { + Type: 'Bar::Baz', + Properties: { Qux: 'Foo' }, + }, + }, + }); + }); }); function expectToThrow(fn: () => void, msgs: (RegExp | string)[]): void {