API 测试
APIRequestContext — HTTP 请求
import { test, expect } from '@playwright/test';
test('GET /api/users', async ({ request }) => {
const response = await request.get('/api/users');
expect(response.status()).toBe(200);
expect(response.ok()).toBeTruthy();
const body = await response.json();
expect(body).toHaveLength(3);
});
test('POST /api/users', async ({ request }) => {
const response = await request.post('/api/users', {
data: { name: '张三', email: 'zhangsan@example.com' },
});
expect(response.status()).toBe(201);
const user = await response.json();
expect(user.id).toBeDefined();
});
响应断言
test('API 响应断言', async ({ request }) => {
const response = await request.get('/api/profile');
expect(response.status()).toBe(200);
expect(response.ok()).toBeTruthy();
expect(response.headers()['content-type']).toContain('application/json');
const json = await response.json();
expect(json).toMatchObject({
id: expect.any(Number),
email: expect.stringContaining('@'),
});
await expect(response).toBeOK();
});
认证存储 — storageState
// global-setup.ts — 登录一次,所有测试复用
import { chromium } from '@playwright/test';
async function globalSetup() {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('http://localhost:3000/login');
await page.fill('#email', 'admin@example.com');
await page.fill('#password', 'adminpass');
await page.click('[type="submit"]');
await page.waitForURL('**/dashboard');
// 保存 cookies + localStorage
await page.context().storageState({ path: 'auth/admin.json' });
await browser.close();
}
// playwright.config.ts
export default defineConfig({
globalSetup: './global-setup.ts',
use: { storageState: 'auth/admin.json' },
});
路由 Mock — page.route()
test('mock API 响应', async ({ page }) => {
await page.route('**/api/users', async route => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([{ id: 1, name: '张三' }]),
});
});
// 中断请求
await page.route('**/*.png', route => route.abort());
await page.goto('/');
await expect(page.getByText('张三')).toBeVisible();
});
API 测试速查表
| 方法 | 用途 |
|---|---|
request.get(url) | HTTP GET 请求 |
request.post(url, {data}) | HTTP POST JSON 请求 |
response.json() | 解析响应为 JSON |
response.status() | 获取 HTTP 状态码 |
page.route(pattern, fn) | 拦截/mock 网络请求 |
storageState | 保存/恢复认证 cookies |