🏄

CDK × TypeScript環境にVitestを導入してLambdaの開発を始めるテンプレート

に公開

概要

CDK × Typescriptを使用てLambdaを作成する場合に必要な設定をまとめて入れたRepositoryを作成
設定内容は以下

  • snapshot testをvitestで実行
  • Lambdaのhash値を固定する設定を追加(おまけ)

急いでる人向け

この記事で説明した手順を実施したテンプレートリポジトリを作成したのでそちらをお使いください。
https://github.com/SumiyaE/cdk-vitest-template

手順

CDK用のプロジェクトを作成

任意の場所に、CDKプロジェクト用のディレクトリを作成

mkdir sample-cdk

cdk init実行し、CDKプロジェクトの作成
※ 今回は言語にTypescriptを指定しています。

❯ cdk init app --language=typescript
Applying project template app for typescript
# Welcome to your CDK TypeScript project

This is a blank project for CDK development with TypeScript.

The `cdk.json` file tells the CDK Toolkit how to execute your app.

## Useful commands

* `npm run build`   compile typescript to js
* `npm run watch`   watch for changes and compile
* `npm run test`    perform the jest unit tests
* `npx cdk deploy`  deploy this stack to your default AWS account/region
* `npx cdk diff`    compare deployed stack with current state
* `npx cdk synth`   emits the synthesized CloudFormation template

Executing npm install...
npm warn deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated glob@7.2.3: Glob versions prior to v9 are no longer supported
✅ All done!

cdk bootstrapの実行
※ コマンドは、CDKプロジェクトのルートディレクトリで実行してください。

❯ cdk bootstrap --profile your_profile_name(自分のprofileに適宜置き換えてください)
 ⏳  Bootstrapping environment aws://xxxxxxxxxxx/ap-northeast-1...
Trusted accounts for deployment: (none)
Trusted accounts for lookup: (none)
Using default execution policy of 'arn:aws:iam::aws:policy/AdministratorAccess'. Pass '--cloudformation-execution-policies' to customize.
CDKToolkit: creating CloudFormation changeset...
 ✅  Environment aws://xxxxxxxxxxx/ap-northeast-1 bootstrapped.

vitestを導入する前にデフォルトでインストールされるjest関連の設定を削除

node_modulesからjest関連のパッケージを削除
※ コマンドは、CDKプロジェクトのルートディレクトリで実行してください。

npm uninstall jest ts-jest @types/jest

removed 273 packages, and audited 64 packages in 853ms

4 packages are looking for funding
  run `npm fund` for details

  found 0 vulnerabilities

jest.config.jsの削除
※ コマンドは、CDKプロジェクトのルートディレクトリで実行してください。

rm jest.config.js

vitestを実行できるよう設定変更

以下のコマンドを実行し、vitestをinstall
※ コマンドは、CDKプロジェクトのルートディレクトリで実行してください。

npm install -D vitest

added 45 packages, and audited 109 packages in 11s

18 packages are looking for funding
  run `npm fund` for details

  found 0 vulnerabilities

package.jsonのtest実行のnpm コマンドを変更
※ コマンドは、CDKプロジェクトのルートディレクトリで実行してください。

{
  "name": "cdk-vitest-template",
  "version": "0.1.0",
  "bin": {
    "cdk-vitest-template": "bin/cdk-vitest-template.js"
  },
  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
-   "test": "jest",
+   "test": "vitest",
    "cdk": "cdk"
  },
  "devDependencies": {
    "@types/node": "22.7.9",
    "aws-cdk": "2.1012.0",
    "ts-node": "^10.9.2",
    "typescript": "~5.6.3",
    "vitest": "^3.1.2"
  },
  "dependencies": {
    "aws-cdk-lib": "2.190.0",
    "constructs": "^10.0.0"
  }
}

vitest用の設定ファイルvitest.config.tstest/以下に作成
※ コマンドは、CDKプロジェクトのルートディレクトリで実行してください。

touch test/vitest.config.ts
vi test/vitest.config.ts

vitest.configの内容は以下

import { defineConfig } from "vitest/config";
export default defineConfig({
  root: ".",
  test: {
    root: ".",
    environment: "node",
    include: ["**/*.{test,spec}.ts"],
  }
});

デフォルトで作成されたtestファイル(test/cdk-sample.test.ts)を編集し、vitestのモジュールを使用して実行できるよう変更

import * as cdk from 'aws-cdk-lib';
import { Template } from 'aws-cdk-lib/assertions';
import * as CdkSample from '../lib/cdk-sample-stack';
import { test, expect } from 'vitest';

test('cdk stack test', () => {
  const app = new cdk.App();
  // WHEN
  const stack = new CdkSample.CdkSampleStack(app, 'TestStack');
  // THEN
  const template = Template.fromStack(stack);


  // 生成したテンプレートとスナップショットが同じであることを確認
  expect(template).toMatchSnapshot();
});

npm testを実行し、vitestが実行できることを確認

npm test

> cdk-sample@0.1.0 test
> vitest


DEV  v3.1.2 ~/myLearning/cdk-sample

 ✓ test/cdk-sample.test.ts (1 test) 85ms
   ✓ cdk stack test 84ms

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  20:12:38
   Duration  668ms (transform 59ms, setup 0ms, collect 385ms, tests 85ms, environment 0ms, prepare 63ms)

 PASS  Waiting for file changes...
       press h to show help, press q to quit

Lambdaのソースコードを編集した時のHash値が固定値になるようなプラグインを追加

こちらの記事を参考に、プラグインを作成
https://dev.classmethod.jp/articles/using-aws-cdk-snapshot-test-serializer-for-multiple-replacement-operations/

Discussion