単体テスト
このガイドでは、MBC CQRS Serverless フレームワークでサービスやハンドラーの単体テストを書く方法を説明します。
依存関係のモック
フレームワークでは @golevelup/ts-jest を使用してモックを作成します。createMock() 関数は、任意のインターフェースやクラスに対してモック実装を自動生成します。
createMock() の基本的な使い方
import { createMock } from '@golevelup/ts-jest'
import { Test } from '@nestjs/testing'
import { ConfigService } from '@nestjs/config'
const moduleRef = await Test.createTestingModule({
providers: [MyService],
})
.useMocker(createMock) // Auto-mock all dependencies (すべての依存関係を自動モック)
.compile()
カスタムモック実装
import { createMock } from '@golevelup/ts-jest'
import { ConfigService } from '@nestjs/config'
const config = {
NODE_ENV: 'test',
APP_NAME: 'my-app',
}
const moduleRef = await Test.createTestingModule({
providers: [
MyService,
{
provide: ConfigService,
useValue: createMock<ConfigService>({
get: jest.fn((key) => config[key] ?? 'default'),
}),
},
],
}).compile()
AWS SDK クライアントのモック
AWS SDK v3 クライアントをモックするには aws-sdk-client-mock を使用します:
import { mockClient } from 'aws-sdk-client-mock'
import 'aws-sdk-client-mock-jest'
import { DynamoDBClient, PutItemCommand, GetItemCommand } from '@aws-sdk/client-dynamodb'
describe('MyService', () => {
const dynamoDBMock = mockClient(DynamoDBClient)
beforeEach(() => {
dynamoDBMock.reset()
})
afterEach(() => {
dynamoDBMock.reset()
})
it('should put item to DynamoDB', async () => {
// Arrange: Set up mock response (準備:モックレスポンスを設定)
dynamoDBMock.on(PutItemCommand).resolves({})
// Action: Execute the method (実行:メソッドを実行)
await myService.saveItem({ pk: 'test', sk: 'item' })
// Assert: Verify the mock was called (検証:モックが呼ばれたことを確認)
expect(dynamoDBMock).toHaveReceivedCommandTimes(PutItemCommand, 1)
expect(dynamoDBMock).toHaveReceivedCommandWith(PutItemCommand, {
TableName: 'my-table',
Item: expect.objectContaining({
pk: { S: 'test' },
sk: { S: 'item' },
}),
})
})
})
完全なテスト例
以下は、フレームワークの実際のテストパターンに基づいた完全な例です:
import { createMock } from '@golevelup/ts-jest'
import { Test } from '@nestjs/testing'
import { mockClient } from 'aws-sdk-client-mock'
import 'aws-sdk-client-mock-jest'
import { DynamoDBClient, GetItemCommand, PutItemCommand } from '@aws-sdk/client-dynamodb'
import { ConfigService } from '@nestjs/config'
const config = {
NODE_ENV: 'test',
APP_NAME: 'my-app',
}
describe('CommandService', () => {
let commandService: CommandService
const dynamoDBMock = mockClient(DynamoDBClient)
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
providers: [
CommandService,
DynamoDbService,
{
provide: ConfigService,
useValue: createMock<ConfigService>({
get: jest.fn((key) => config[key]),
}),
},
],
})
.useMocker(createMock) // Auto-mock remaining dependencies (残りの依存関係を自動モック)
.compile()
commandService = moduleRef.get<CommandService>(CommandService)
})
afterEach(() => {
jest.clearAllMocks()
dynamoDBMock.reset()
})
describe('getLatestItem', () => {
it('should return the latest item', async () => {
// Arrange (準備)
const key = { pk: 'master', sk: 'test' }
// Action (実行)
const item = await commandService.getLatestItem(key)
// Assert (検証)
expect(item).toBeDefined()
expect(item?.pk).toBe('master')
})
it('should return null when item not found', async () => {
// Arrange (準備)
const key = { pk: 'master', sk: 'nonexistent' }
// Action (実行)
const item = await commandService.getLatestItem(key)
// Assert (検証)
expect(item).toBeNull()
})
})
})
CommandService 向けの DynamoDbService のモック
バージョン 1.7.0 以降、CommandService はすべての初回コマンドを、putItem を直接呼ぶ代わりに DynamoDbService.putItemWithConditions 経由で書き込みます。
実際の putItemWithConditions は、アドミッション条件が返されない場合に自身で putItem を呼びます。実際の CommandService を動かすテストへの影響は、DynamoDbService のモック方法によって異なります:
| モックの方法 | v1.7.0 以降の動作 | 対応 |
|---|---|---|
実際の DynamoDbService(例: aws-sdk-client-mock を使用、または putItem に jest.spyOn) | 引き続き動作する: 条件がない場合、putItemWithConditions は putItem に委譲する | 不要 |
putItem だけを定義した手書きのモック | putItemWithConditions is not a function で失敗する | putItemWithConditions を追加する |
createMock()(@golevelup/ts-jest)による自動モック | 例外は出ないが、putItemWithConditions が自動モックされるため putItem に到達しない。putItem に対するアサーションが原因の分かりにくい形で失敗する | putItemWithConditions をアサートするか、putItem を呼ぶようにスタブする |
putItem のモックに委譲すると 、既存のアサーションはそのまま動作します:
{
provide: DynamoDbService,
useValue: {
getItem: jest.fn(),
putItem: jest.fn(async (tableName, item) => item),
// Delegate to putItem so existing putItem assertions still pass (既存の putItem のアサーションが通るように putItem に委譲する)
putItemWithConditions: jest.fn(function (tableName, item, condition) {
return this.putItem(tableName, item, condition)
}),
},
},
自動モックの場合は、putItemWithConditions を直接アサートするか、同じようにスタブしてください:
const dynamoDbService = moduleRef.get(DynamoDbService)
// Option 1: assert on the method CommandService now calls (方法 1: CommandService が呼ぶようになったメソッドをアサートする)
expect(dynamoDbService.putItemWithConditions).toHaveBeenCalledWith(
'test-table',
expect.objectContaining({ pk: 'TENANT#test' }),
'attribute_not_exists(pk) AND attribute_not_exists(sk)',
[],
)
// Option 2: route it to the putItem auto-mock before the test runs (方法 2: テスト実行前に putItem の自動モックへ転送する)
jest
.mocked(dynamoDbService.putItemWithConditions)
.mockImplementation((tableName, item, condition) =>
dynamoDbService.putItem(tableName, item, condition),
)
この動作は フレームワークのリリース準備(PR #516)で @golevelup/ts-jest 0.5.6 を使って確認されました。CLI テンプレートは ^0.6.1 に依存しています。
getCommandAdmissionConditions をオーバーライドしたサブクラスをテストする場合は、putItemWithConditions の第 4 引数として渡されるチェックをアサートしてください。モックでは DynamoDB の atomic 性を証明できないため、そのようなコードは DynamoDB Local でも実行してください。
主要なテストパターン
テスト構造
各テストは Arrange-Act-Assert パターンに従います:
- Arrange (準備): テストデータとモックレスポンスを設定
- Act (実行): テスト対象のメソッドを実行
- Assert (検証): 結果とモックの呼び出しを検証
describe と it の使い方
関連するテストをグループ化す るには describe を使用し、個々のテストケースには it を使用します:
describe('ServiceName', () => {
describe('methodName', () => {
it('should do something when condition is met', async () => {
// test implementation (テスト実装)
})
it('should throw error when input is invalid', async () => {
// test implementation (テスト実装)
})
})
})
エラーケースのテスト
import { BadRequestException } from '@nestjs/common';
it('should throw BadRequestException when item not found', async () => {
const invalidKey = { pk: 'invalid', sk: 'key', version: 1 }
await expect(
commandService.publishPartialUpdateAsync(invalidKey, { invokeContext: {} })
).rejects.toThrow(BadRequestException)
})
高度なAWS SDKモックパターン
複数のAWSサービスのモック
複数のAWSサービスと対話するサービスをテストする場合、各クライアントのモックを設定します:
import { mockClient } from 'aws-sdk-client-mock'
import 'aws-sdk-client-mock-jest'
import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb'
import { SNSClient, PublishCommand } from '@aws-sdk/client-sns'
import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs'
describe('MultiServiceTest', () => {
const dynamoMock = mockClient(DynamoDBClient)
const snsMock = mockClient(SNSClient)
const sqsMock = mockClient(SQSClient)
beforeEach(() => {
dynamoMock.reset()
snsMock.reset()
sqsMock.reset()
})
it('should publish to SNS after saving to DynamoDB', async () => {
dynamoMock.on(PutItemCommand).resolves({})
snsMock.on(PublishCommand).resolves({ MessageId: 'msg-123' })
await myService.saveAndNotify(data)
expect(dynamoMock).toHaveReceivedCommandTimes(PutItemCommand, 1)
expect(snsMock).toHaveReceivedCommandTimes(PublishCommand, 1)
})
})
条件付きレスポンスのモック
入力に基づいて異なるレスポンスを返すには callsFake を使用します:
import { marshall } from '@aws-sdk/util-dynamodb'
dynamoMock.on(GetItemCommand).callsFake((input) => {
if (input.Key.pk.S === 'existing-key') {
return {
Item: marshall({
pk: 'existing-key',
sk: 'item',
name: 'Test Item',
}),
}
}
return { Item: undefined } // Item not found (アイテムが見つかりません)
})