0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AWS CDK で snapshot を実施する

Posted at

CDK Snapshot Test とは

スナップショットと比較して、合成された CloudFormation テンプレートに差分がないかを確認するテストになります。
また、jestなど各言語固有のテストコマンドで実行されます。

実施のための準備

  • 必要パッケージを入れる
npm install --save-dev jest ts-jest @types/jest @aws-cdk/assertions

# jest → テストの実行基盤
# ts-jest → TypeScript のテストをトランスパイル
# @types/jest → Jest の型定義(TS用)
# @aws-cdk/assertions → CDKのテンプレート取得&検証
  • Jest設定を作る
npx ts-jest config:init

# jest.config.jsファイルが出来上がる
  • テストフォルダを作成する
mkdir __test__
  • テストファイルを作成する
// そのまま貼っていますが、ココは作成しているリソースに応じて変わるため、生成AIなどでよしなに作った方が良さそう
import { Template } from 'aws-cdk-lib/assertions';
import * as cdk from 'aws-cdk-lib';
import { AmazonLinux2023 } from '../lib/EC2/AmazonLinux2023';

describe('AmazonLinux2023 Stack Snapshot', () => {
  test('スタックの構造が期待通りである', () => {
    const app = new cdk.App();
    
    // 実際のAWS環境に接続するための設定
    const stack = new AmazonLinux2023(app, 'TestAmazonLinux2023Stack', {
      env: {
        account: process.env.CDK_DEFAULT_ACCOUNT || 'NNNNNNNNN',  // 実際のアカウントID
        region: process.env.CDK_DEFAULT_REGION || 'ap-northeast-1'   // 実際のリージョン
      }
    });
    
    const template = Template.fromStack(stack);
    expect(template.toJSON()).toMatchSnapshot();
  });
});

実施

  • テストを実施する
npm test
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?