用途
本技能面向 REST 与 GraphQL 接口测试场景,使用 Playwright 内置的 API 测试能力完成接口请求、响应断言、端点模拟,以及将 API 测试与端到端(E2E)流程结合。适用于测试 API、模拟端点、校验响应,或把接口测试集成进 E2E 流程时。
主要能力
- REST API 测试:覆盖 GET(如按 ID 获取用户)、POST(创建资源,断言 201 状态)、PUT/PATCH(更新资源)、DELETE(断言 204 并验证删除后返回 404)。
- 认证测试:支持 Bearer Token(通过登录接口获取 token 并在请求头中携带)与基于 Cookie 的认证(登录后 Cookie 自动包含于后续请求)。
- GraphQL 测试:支持 query 查询与 mutation 变更,可传入 variables,并可通过请求头携带认证信息。
- API 模拟(用于 E2E 测试):使用 page.route 模拟接口响应、模拟错误(如 500)、延迟响应(验证加载状态)。
- 响应校验:使用 Ajv 进行 JSON Schema 校验;检查响应头(如 content-type、x-rate-limit-remaining)。
- 文件上传:通过 multipart 发送文件(含 name、mimeType、buffer)及附加字段。
使用方式
安装:Playwright 已包含 API 测试能力,无需额外包。
npm install -D @playwright/test
配置示例(playwright.config.ts)中可设置 testDir、baseURL、extraHTTPHeaders(如 Accept: application/json),并通过 projects 区分 api(testMatch 匹配 *.api.spec.ts)与 e2e(匹配 *.e2e.spec.ts,使用 chromium)。
测试示例(来自资料):
import { test, expect } from '@playwright/test';
test('GET /api/users returns users', async ({ request }) => {
const response = await request.get('/api/users');
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
const users = await response.json();
expect(users).toHaveLength(10);
expect(users[0]).toHaveProperty('email');
});
GraphQL 示例(查询用户):
test('GraphQL query users', async ({ request }) => {
const response = await request.post('/graphql', {
data: {
query: `
query GetUsers {
users {
id
name
email
}
}
`,
},
});
const { data, errors } = await response.json();
expect(errors).toBeUndefined();
expect(data.users).toHaveLength(10);
});
模拟示例(E2E 中模拟商品接口):
test('display mocked products', async ({ page }) => {
await page.route('**/api/products', route => {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 1, name: 'Mock Product', price: 99.99 },
]),
});
});
await page.goto('/products');
await expect(page.locator('.product')).toHaveCount(1);
await expect(page.locator('.product-name')).toHaveText('Mock Product');
});
JSON Schema 校验示例使用 Ajv:
import Ajv from 'ajv';
const ajv = new Ajv();
const userSchema = {
type: 'object',
properties: {
id: { type: 'number' },
name: { type: 'string' },
email: { type: 'string', format: 'email' },
},
required: ['id', 'name', 'email'],
};
test('validate response schema', async ({ request }) => {
const response = await request.get('/api/users/1');
const user = await response.json();
const validate = ajv.compile(userSchema);
expect(validate(user)).toBeTruthy();
});
适用场景
- 对 REST 接口进行功能与状态码断言。
- 对 GraphQL 查询与变更进行测试。
- 在 E2E 测试中模拟外部接口、错误与延迟,以验证前端展示与容错。
- 通过 JSON Schema 与响应头校验提前发现破坏性变更。
- 上传文件接口的测试。
最佳实践(来自资料)
- 分离 API 与 E2E 测试,使用不同测试文件/项目。
- 使用 fixtures 复用公共数据,避免重复。
- 测试错误场景:400、401、403、404、500 响应。
- 校验响应 schema,尽早发现破坏性变更。
- 模拟外部 API,避免依赖第三方可用性。
- 清理测试数据,使用 afterEach 或 afterAll 钩子。
参考资料(来自资料)
- references/graphql-testing.md:高级 GraphQL 模式。
- references/schema-validation.md:使用 Ajv 的 JSON Schema 校验。
限制
资料未提供收费、价格、平台支持范围等具体信息;除已列出内容外,其余信息暂未提供。