ウェブアプリケーションの自動化テストは、外部APIとのやり取りを必要とすることがよくあります。しかし、実際のAPIのレスポンスに依存すると、ネットワーク問題やサーバーダウンタイムなど、制御不可能な変数が発生する可能性があります。これにAPIモッキングが登場します。モッキングにより、APIのレスポンスをシミュレートすることができ、テストの信頼性と速度を向上させることができます。この記事では、Playwrightを使用してTypeScriptでAPIをモッキングする方法を探ります。
PlaywrightでのAPIモッキング
Playwrightは、route
メソッドを使用してネットワークリクエストを横取りし、レスポンスをモッキングする方法を提供します。APIのレスポンスをモッキングする例を一歩一歩見ていきましょう。
ステップバイステップガイド
1. 必要なモジュールをインポート + 基本的なテストを作成
TypeScript
import { test, expect, chromium } from '@playwright/test';
test('Mock User Profile API', async ({ page }) => {
await page.goto('https://example.com/profile');
// ここでモッキングを行います
});
2. リクエストの横取りとモッキングのセットアップ
TypeScript
test('Mock User Profile API', async ({ page }) => {
// シナリオ1: 成功したデータ取得
await page.route('https://api.example.com/user/profile', route => {
const mockResponse = {
status: 200,
contentType: 'application/json',
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]',
age: 30
})
};
route.fulfill(mockResponse);
});
await page.goto('https://example.com/profile');
const userName = await page.textContent('#name'); // Assuming the name is rendered in an element with id 'name'
const userEmail = await page.textContent('#email'); // Assuming the email is rendered in an element with id 'email'
const userAge = await page.textContent('#age'); // Assuming the age is rendered in an element with id 'age'
expect(userName).toBe('John Doe');
expect(userEmail).toBe('[email protected]');
expect(userAge).toBe('30');
});
3. より多くのシナリオを追加
TypeScript
test('Mock User Profile API - Empty Profile', async ({ page }) => {
// シナリオ2: 空のユーザープロファイル
await page.route('https://api.example.com/user/profile', route => {
const mockResponse = {
status: 200,
contentType: 'application/json',
body: JSON.stringify({})
};
route.fulfill(mockResponse);
});
await page.goto('https://example.com/profile');
const userName = await page.textContent('#name');
const userEmail = await page.textContent('#email');
const userAge = await page.textContent('#age');
expect(userName).toBe('');
expect(userEmail).toBe('');
expect(userAge).toBe('');
});
test('Mock User Profile API - Server Error', async ({ page }) => {
// シナリオ3: サーバーエラー
await page.route('https://api.example.com/user/profile', route => {
const mockResponse = {
status: 500,
contentType: 'application/json',
body: JSON.stringify({ error: 'Internal Server Error' })
};
route.fulfill(mockResponse);
});
await page.goto('https://example.com/profile');
const errorMessage = await page.textContent('#error'); // Assuming the error message is rendered in an element with id 'error'
expect(errorMessage).toBe('Internal Server Error');
});
テストの実行
npx playwright test
高度なモッキング技術
Playwrightは、条件付きのレスポンスや遅延など、より高度なモッキング技術を可能にします。以下は、条件付きのモックの例です:
TypeScript
test('Conditional Mocking', async ({ page }) => {
await page.route('https://api.example.com/user/profile', route => {
if (route.request().method() === 'POST') {
route.fulfill({
status: 201,
contentType: 'application/json',
body: JSON.stringify({ message: 'Profile created' })
});
} else {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]',
age: 30
})
});
}
});
await page.goto('https://example.com/profile');
// ここに追加のテストロジックを記述します
});
また、ネットワークの遅延をシミュレートする遅延を導入することもできます:
TypeScript
test('Mock with Delay', async ({ page }) => {
await page.route('https://api.example.com/user/profile', async route => {
await new Promise(res => setTimeout(res, 2000)); // Delay for 2 seconds
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
name: 'John Doe',
email: '[email protected]',
age: 30
})
});
});
await page.goto('https://example.com/profile');
// ここに追加のテストロジックを記述します
});
総じて
Playwrightを使ってTypeScriptでAPIをMockingするは強力なテクニックであり、これはテストの信頼性と速度を高めます。ネットワーク要求を阻止し、独自の応答を提供することで、さまざまなシナリオをシミュレートし、アプリケーションが異なる条件で期待どおりの動作を保証できます。
このガイドがPlaywrightテストでAPI mockを始めるに役立つことを期待します。楽しいテストを!
Source:
https://dzone.com/articles/effortless-api-mocking-with-playwright