cdk-stacksets icon indicating copy to clipboard operation
cdk-stacksets copied to clipboard

Unable to write unit tests for StackSetStacks

Open nhaynes opened this issue 11 months ago • 0 comments

I've been trying to write a CDK unit test for my StackSetStack but I keep running into issues with this no matter how I structure it.

Targeting the Parent Stack

With this setup, the test runs but the template that is synthesized is not of any interest to me as it only contains the inner workings (Lambda, CustomResource, Assets, etc.) that makes cdk-stacksets function but it doesn't contain any of the details of my MyStackSetStack that I would like to test.

it('matches the snapshot', () => {
  const app = new App();
  const stack = new Stack(app, 'TestStack');
  const stackSetStack = new MyStackSetStack(stack, 'MyStackSetStack', {
    assetBuckets: [Bucket.fromBucketName(stack, 'Assets', 'stackset-assets-us-east-2')],
    assetBucketPrefix: 'stackset-assets',
  });

  const template = Template.fromStack(stack);

  expect(template).toMatchSnapshot();
});

Targeting the StackSetStack

Since StackSetStack extends Stack, I figured I could just switch Template.fromStack to target the stackSetStack directly and then I would get the template I want to run my tests against.

But with this setup, I always get this error:

Unable to find artifact with id "TestStackMyStackSetStackXXXXXXXX"

  const app = new App();
  const stack = new Stack(app, 'TestStack');
  const stackSetStack = new MyStackSetStack(stack, 'MyStackSetStack', {
    assetBuckets: [Bucket.fromBucketName(stack, 'Assets', 'stackset-assets-us-east-2')],
    assetBucketPrefix: 'stackset-assets',
  });

  const template = Template.fromStack(stackSetStack);

  expect(template).toMatchSnapshot();

Removing Parent Stack All Together

Next I tried to just remove the Parent stack entirely and just create the MyStackSetStack on the app itself.

But this gave me this error because of the asset bucket:

App at '' should be created in the scope of a Stack, but no Stack found

image

  const app = new App();
  const stackSetStack = new MyStackSetStack(app, 'MyStackSetStack', {
    assetBuckets: [Bucket.fromBucketName(app, 'Assets', 'stackset-assets-us-east-2')],
    assetBucketPrefix: 'stackset-assets',
  });

  const template = Template.fromStack(stackSetStack);

  expect(template).toMatchSnapshot();

Removing Asset Bucket

So my last attempt was to do it without the asset bucket but this resulted in this error:

image

  const app = new App();
  const stackSetStack = new MyStackSetStack(app, 'MyStackSetStack', {
    assetBuckets: [Bucket.fromBucketName(app, 'Assets', 'stackset-assets-us-east-2')],
    assetBucketPrefix: 'stackset-assets',
  });

  const template = Template.fromStack(stackSetStack);

  expect(template).toMatchSnapshot();

Again, since the StackSetStack is a Stack, it would be nice if we could test them just like we do any other AWS CDK stack.

nhaynes avatar Mar 02 '24 00:03 nhaynes