自動化網絡應用测试通常需要與外部API進行互動。然而,依賴於實際的API响应可能會引入無法控制的變量,例如網絡問題或服務器宕機。這時API模拟就派上用場了。模拟允許你模擬API响应,使你的測試更加可靠和快速。在本文中,我們將探索如何使用TypeScript和Playwright模擬API。
在Playwright中模擬APIs
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 是一個強大的技術,可以提高您的測試可靠性和速度。通過截取網絡請求並提供自定義響應,您可以模擬各種情境,並確保您的應用程序在不同的條件下如预期般行為。
我希望這篇指南能幫助您開始在 Playwright 測試中使用 API 模仿。快樂測試!
Source:
https://dzone.com/articles/effortless-api-mocking-with-playwright