Previous
Day 16 · Authentication and Reusing Login State
Next
Day 18 · Network Interception and Mocking
真实场景
Day 1760-120 minutesPlaywright QA hands-on drill

Day 17 - API Testing

今日目标

  • 使用 Playwright 做 API 测试。
  • 理解 UI 测试与 API 测试如何配合。

学习时间安排(60–120 分钟)

时间模块做什么
0-20 分钟核心概念与词汇读概念表,重点理解 request fixture 和 APIRequestContext。
20-45 分钟官方文档阅读读 API testing 文档的 intro 和 request fixture 部分。
45-75 分钟实操练习写 3 条 API 测试:GET 列表、POST 创建、DELETE 清理。
75-105 分钟示例代码改写把一条 UI 流程的“准备数据”步骤改成 API 调用。
105-120 分钟复盘与作业完成今日问题,总结 UI+API 组合测试思路。

核心概念与词汇

English中文场景用法
request fixture请求夹具Use it when you send HTTP requests directly in tests.
APIRequestContextAPI 请求上下文Use it when you reuse cookies and headers from the browser context for API calls.
response.ok()响应成功判断Use it when you check the status code is 2xx.
response.json()JSON 解析Use it when you read and assert the response body.
status code状态码Use it when you assert 200, 201, 204, 404, 500 responses.
GET / POST / PUT / DELETEHTTP 方法Use it when you read, create, update, or delete resources.
test data setup测试数据准备Use it when API calls create prerequisites faster than UI flows.
cleanup数据清理Use it when API calls delete test data after the test.
payload请求体Use it when you describe the JSON body sent with a request.
health check健康检查Use it when an API test verifies the service is up before UI tests.

学习材料

  • 必读:[API testing](https://playwright.dev/docs/api-testing)
  • 必读:[APIRequestContext](https://playwright.dev/docs/api/class-apirequestcontext)(浏览主要方法)
  • 选读:[Test fixtures - request](https://playwright.dev/docs/test-fixtures#request)

重点理解

示例:

import { test, expect } from '@playwright/test';

test('api test', async ({ request }) => {
  const response = await request.get('/api/users');
  expect(response.ok()).toBeTruthy();

  const body = await response.json();
  expect(body.length).toBeGreaterThan(0);
});

应用场景:

  • 准备测试数据。
  • 清理测试数据。
  • 校验后端状态。
  • 替代部分慢 UI 操作。
  • 做接口健康检查。

实操步骤

写 3 条 API 测试:

  1. GET 列表。
  2. POST 创建数据。
  3. DELETE 清理数据。

如果没有真实 API,可以用公开测试 API 或本地 mock server。

示例代码

import { test, expect } from '@playwright/test';

test.describe('user api', () => {
  test('create and delete a user', async ({ request }) => {
    // POST 创建测试数据
    const createRes = await request.post('/api/users', {
      data: { username: 'auto_test_user', role: 'tester' },
    });
    expect(createRes.ok()).toBeTruthy();
    const user = await createRes.json();

    // GET 校验创建结果
    const getRes = await request.get(`/api/users/${user.id}`);
    expect(getRes.ok()).toBeTruthy();
    expect(await getRes.json()).toMatchObject({ username: 'auto_test_user' });

    // DELETE 清理数据
    const deleteRes = await request.delete(`/api/users/${user.id}`);
    expect(deleteRes.ok()).toBeTruthy();
  });
});

常见坑

  • response.status() 手写 expect(status).toBe(200) 也行,但忘了 response.ok() 覆盖整个 2xx 范围。
  • API 测试和 UI 测试混在同一个文件里,职责不清。
  • 创建了数据却忘了 DELETE 清理,第二次运行重复数据冲突。
  • API 用的 baseURL 与 UI 不一致,环境切换时一半请求打错环境。
  • 把 API 测试当成 UI 测试的替代品,丢掉了真实用户路径的验证。

今日产出

  • 一个 api.spec.ts
  • 一套 UI + API 组合测试思路。

今日问题

  1. Playwright 的 request fixture 是什么?
  2. 哪些场景适合 API 测试,不适合 UI 测试?
  3. API 创建测试数据有什么好处?
  4. UI 和 API 断言如何互相补充?
  5. API 测试失败和 UI 测试失败如何区分?

复盘要点

  • 测试金字塔提示我们:数据准备用 API,关键用户路径用 UI,两者组合而不是互相替代。
  • API 测试快、稳定、定位精确,是回归集的主力;UI 测试覆盖端到端体验。
  • 每个写操作的 API 测试都要有对应的清理路径,这是数据卫生的基本功。

AI 时代扩展:AI 辅助 Playwright 测试

新增概念

English中文
API test generationAPI 测试生成
contract verification契约校验
data seeding数据播种

适用场景

让 AI 根据接口文档或响应示例生成 API 测试草稿,或者帮你设计“UI 验证 + API 准备数据”的组合流程。

可复用表达 / 提示词

这是接口文档:GET /api/orders 返回订单列表。请生成 3 条 API 测试草稿:正常、空数据、分页参数。
我的 UI 测试需要预先存在一个订单,请设计用 API 创建并清理该订单的完整流程。

追问加练

  • AI 生成的 API 测试没有断言响应结构,你怎么补?
  • 让 AI 从响应示例生成断言,风险是什么?
  • 清理失败时(DELETE 报错),测试策略上怎么兜底?

今日作业

  • 完成 3 条 API 测试并跑通。
  • 把你的一条 UI 测试改造成“API 准备数据 + UI 验证 + API 清理”。
  • 让 AI 根据你的接口响应生成断言草稿,人工核对后使用。

自检清单

Previous
Day 16 · Authentication and Reusing Login State
Next
Day 18 · Network Interception and Mocking