API Assertions
API tests in Playwright use request fixture or page.request to call HTTP endpoints and assert on status, headers, and JSON bodies — fast complements to UI tests.
Testing HTTP Responses APIResponse provides status(), json(), text(), headers(), and ok(). Use generic expect on parsed JSON for structure and values.
API tests skip browser rendering — ideal for contract validation, auth token exchange, and edge cases expensive to reach through UI.
test('GET /api/users', async ({ request }) => {
const response = await request.get('/api/users');
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
const body = await response.json();
expect(body.users).toHaveLength(3);
expect(body.users[0]).toMatchObject({ email: expect.stringContaining('@') });
}); Use request fixture with baseURL from config.
API Assertion Patterns const res = await request.post('/api/login', { data: { user, pass } });
expect(res.status()).toBe(401);
const { token } = await res.json();
expect(token).toBeDefined(); request shares config baseURL and extra HTTP headers. Pass data for JSON body, form for form encoding, multipart for uploads. Use storageState on request context for authenticated API calls. Schema validation via zod/ajv optional but recommended for contracts. API Assertion Reference Common checks on APIResponse.
Check Code Success expect(res.ok()).toBeTruthy() Status code expect(res.status()).toBe(201) Header expect(res.headers()['content-type']).toContain('json') JSON field expect(body.id).toBeDefined() Array length expect(body.items).toHaveLength(5) Partial object toMatchObject({ role: 'admin' })
Authenticated API Requests test.use({ storageState: 'auth/user.json' });
test('profile API', async ({ request }) => {
const res = await request.get('/api/me');
expect(res.status()).toBe(200);
}); The toBeOK Matcher await expect(response).toBeOK() asserts status 200–299. Combine with expect(await response.json()) for body validation on API tests.
Common Mistakes Only testing happy path status 200. Not awaiting response.json() before assertions. Hardcoding full API URL when baseURL + path suffices. Duplicating every UI test at API level — test pyramid balance. Key Takeaways APIRequestContext enables fast HTTP-level tests. Combine status, header, and body assertions. Reuse storageState for authenticated endpoints. Use API tests for contracts; UI tests for integration.
Pro Tip
Seed data via API in beforeEach instead of clicking through admin UI — saves minutes per test in large suites.
Locator Assertions Go to next item