JEST Snapshot Testing with CDK for EC2 Instance, Detect changes Before Deployment

As well as CDK creation and deployment of the stack are also covered in these document.

We need Following things-:

  1. NodeJs Environment

  2. IDE (Here we use VS code)

  3. Typesript

  4. CDK

Install NodeJs

Create Project

  • Open vs code

    • Open Terminal

      • command ~

          mkdir my-project
          cd my-project
          cdk init app --language typescript
        
    • All files are created automatically

    • image

Install Configuration

  • Npm

    • Install AWS CDK and Jest

        npm install aws-cdk
        npm install aws-cdk-lib aws-cdk @types/node --save
        npm install --save-dev jest @types/jest ts-jest
      
  • Update your package.json to include Jest configuration:

    • Code

        {
          "scripts": {
            "test": "jest"
          },
          "jest": {
            "preset": "ts-jest",
            "testEnvironment": "node"
          }
        }
      

Define your CDK Stack

  • Navigate to the lib/ directory and edit the TypeScript file (e.g., my-ec2-stack.ts) to define your EC2 stack using the AWS CDK:

    • Code accroding to your stack - This is mine

Write Jest test

  • Create a Jest test file (e.g., my-ec2-stack.test.ts) in the test/ directory:

    • Code for Jest

Install dependencies

  • npm install

    • IMAGE

Run Jest Tests

  • npm test

    • image

Deployment Stage

  • Bootstrapping- Deploys the CDK Toolkit staging stack

    • Bootstrapping is the process of provisioning resources for the AWS CDK before you can deploy AWS CDK apps into an AWS environment. (An AWS environment is a combination of an AWS account and Region).

      • Command

          cdk bootstrap aws://<AWS_ACCOUNT_ID>/<AWS_REGION>
        
  • Synthesize

    • Synthesizes and prints the CloudFormation template for one or more specified stacks.

    • This allows you to review the generated CloudFormation code before deploying it.

      • command

          cdk synth
        
  • Deploy Your CDK Application

    • This command will orchestrate the creation of the resources specified in your CDK code.

      • command

          cdk deploy
        
    • Now check the AWS cloud formation stack has been created and also it shows in terminal.

Cleanup (Optional):

  • If needed, you can run the cdk destroy command to delete the resources created by your CDK application.

    
      cdk destroy