Ensure that Template.fromStack() includes resources with the specified logical identifiers

Currently, I am overhauling a CDK stack in TypeScript that has reached the resource limit. Given that it includes stateful resources, I need to ensure that the revamped stack points to the same resources and not new ones that could lead to unfavorable results such as orphaning or deletion.

In order to tackle this issue, my goal is to write a unit test that verifies the template produced from a stack consists of resources with specified logical IDs. While there are methods to confirm the existence of resources with certain properties, I have yet to come across a way to validate the presence of resources based on their IDs.

Is there a way for me to verify that a stack comprises resources with specific logicalIDs? Ideally, I would like to accomplish something similar to the example below:


describe('MyStack', () => {
  test('synthesizes with expected logical IDs', () => {
    const app = new cdk.App();
    const stack = new MyStack(app, 'MyStackDev', {
      deploymentEnvironment: 'dev',
    });

    const template = Template.fromStack(stack);

    const expectedLogicalIds = [
      apiGatewayDev,
      lambdaDev,
      webSocketLambdaDev,
      devLambdaWithConcurrentProvisioning,
      neptuneBastionHostDev,
      neptuneClusterDev,
      auroraClusterDev,
      sevenndevimages,
      sevenndevprivate,
      sparkQueryLogs,
      shareLinks,
      webSocketInstances,
      flowInteractionLog,
    ];

    expectedLogicalIds.forEach((logicalId) => {
      // NOTE: if I need to apply the type, then I'll need to do some more work
      //       to make sure the right type is matched with the right logical id
      //       either way, I don't expect it to work as written because I don't
      //       believe this is proper usage of hasResourceProperties, as the 
      //       logical id is actually the key of the resource object
      expect(
        template.hasResourceProperties('AWS::Lambda::Function', { LogicalId: logicalId }),
      ).toBeTruthy();
    });
  });
});

Answer №1

Ensuring that the resource type matches is crucial for safety.

To verify the logical IDs, you can utilize .templateMatches():

expect(
  template.templateMatches({
    Resources: {
      // This is your logical ID, which is the key of the resource object
      [lambdaDev]: {
        Type: "AWS::Lambda::Function",
      },
    },
  }),
).toBeTruthy();

This approach works because it allows specifying a subset of the template. According to the documentation:

By default, the templateMatches() API will use an 'object-like' comparison, permitting the actual template to be a superset of the provided expectation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover a method for bypassing the Quick Search Firefox feature and capturing the forward slash keypress

Currently, I am trying to capture the key press value of '191' for the forward slash (/) as part of a feature on my website. This functionality works perfectly on all browsers except for Firefox, where it conflicts with the Quick Search feature. ...

Steps for transferring data from one flatlist to another (an array of objects) within the same page featuring identical data:

const DATA = [ { car_name: 'Ford', model_number: '2021 . 68 - 1647', full_tank: false, suggestion: [ { price: '$2.50', type: 'Oil Top up&apos ...

Outputting PHP variables in JavaScript is a common practice used to pass

I am struggling to use a variable in my JavaScript code. I have attempted a few methods but none seem to work. The variable I need to include in the JavaScript is option-<?php echo $option['product_option_id']; ?> Below is my current Java ...

Location appearing feature activated by clicking on navigation buttons

I've been having trouble getting the navigation locations to appear and disappear. I'm not very familiar with JavaScript, but I suspect that's the issue. My goal is to make the locations (WebDesign, Photography, SketchUp, Photoshop, About, H ...

Is there a way to receive autocomplete suggestions for sequelize classes that extend the Model class?

I have a specific Post class that I've created with various properties defined within it. However, I often find myself struggling to remember all the fields when actually typing them out, leading to errors in my code. @Table class Post extends Model { ...

Compiled TypeScript files are missing require statements for imported components

Recently delved into Angular 2 and encountered an unusual issue. I kicked off using the Angular 2 Quickstart repository on GitHub and incorporated some components with templates. For example: import { Component } from '@angular/core'; import { ...

Retrieve the component information from the JavaScript function located outside of the main code

Is there a way to retrieve the component data using an external JavaScript function? I am looking to access markers, labels, and images. Vue.component('home', { template: '#home', data: () => ({ markers: [ ...

Do interfaces in Typescript require nested properties to be mandatory?

My interface contains a nested object: export interface Person { PersonWrapper: { name: string; address: string email?: string; } } When attempting to create an object from this interface, it appears that name is not mandat ...

Issue: [ng:areq] The parameter 'TasksCtrl' should be a function, but it is currently undefined

I seem to be encountering an error and I'm struggling to identify the cause. Is there something I overlooked? js var app = angular.module('Todolist', []); app.controller('TasksCtrl', [ '$scope', function($scope) { ...

Adding plain HTML using jQuery can be done using the `.after()` and `.before()` methods

I have encountered a situation where I need to insert closing tags before an HTML element and then reopen it with the proper tags. The code snippet I am using is as follows: tag.before("</div></div>"); and then re-open it by adding proper tag ...

What are some alternatives to using multiple slot transclution in an Angular 1.5 component?

In the process of constructing a panel component using angular 1.5, I am looking to embed some markup into this template (which has been simplified): <div class="panel"> <h1>{{ $ctrl.title }}</h1> <div ng-transclu ...

What is the best way to start the server when the files are located in separate directories?

I have organized my project into two separate folders, one for the client and one for the server Is there a way to use npm start to simultaneously run both the frontend and backend scripts? Check out the screenshot below: View of Two Folders in my Projec ...

Failure to load a picture does not trigger onError in the onLoad function

Is there a way to ensure that an image always loads, even if the initial load fails? I have tried using the following code snippet: <img class="small" src="VTVFile4.jpg" onload="this.onload=null; this.src='VTVFile4.jpg?' + new Date();" alt=" ...

Creating a Select component in React without relying on the Material-UI library involves customizing a dropdown

Is there a way to achieve a material UI style Select component without using the material UI library in my project? I'm interested in moving the label to the top left corner when the Select is focused. export default function App({...props}) { retu ...

Dead keyup event using jQuery live in SignalR invocation

I am working on a sample chat application using SignalR, but I'm facing an issue with my keyup event not functioning properly. Below is the code snippet: // Keyup event for text box $(".ChatText").on('keyup', function () { if($(".ChatTe ...

Reconfigure the Node application using Express to seamlessly access modules through route files

I recently created a basic app using npm express. After generating the app.js file, I attempted to add new modules but encountered an issue where I couldn't access them in the route files. For example, when trying to utilize the 'request' mo ...

Is it possible to implement pagination for API requests in a JavaScript and React environment?

I am currently working on an app that fetches data from a movie API and returns 20 items from page 1. I am now looking to implement pagination so that users can click a button to view more items from subsequent pages. Below is my current API call: export ...

Attempting to utilize a Python web scraping tool to extract content from a webpage that undergoes regular text updates

I must admit that I am a complete beginner who is feeling lost and unsure of what to do. My goal is to extract 4 pairs of numbers from a webpage using a web scraper. These numbers change when modified on a different page, but I'm unable to pull the d ...

Utilizing Google Caja for JavaScript sanitization is the only way to ensure

Looking to safeguard the inputs provided to a nodejs server with the assistance of the google-caja sanitizer. However, it's somewhat overzealous and cleanses away the > and < symbols too. My project requires me to retain html characters in the ...

how can a loop be used to continuously call a function that returns a stream?

I'm faced with a challenge involving a function that validates items using the following definition: validate(item: ValidationItem): Observable<ValidationResult>{} My task now is to develop a function that can iterate through an array of Valid ...