Network & API
Route, mock, and inspect network traffic during browser tests.
Route Interception
page.route(urlPattern, handler) intercepts requests before they hit network. handler can fulfill mock response, continue with modifications, or abort.
Register routes before navigation triggering requests. Unroute when test completes if reusing page across scenarios.
await page.route("**/api/products", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify([{ id: 1, name: "Widget" }]),
});
});Mock Responses
fulfill with status, headers, body simulates API. route.fetch gets original response for passthrough modification—useful for adding test header while hitting real backend.
Mock errors (500, 429) to verify UI resilience without breaking staging API.
await page.route("**/api/user", (route) =>
route.fulfill({ status: 401, body: JSON.stringify({ error: "Unauthorized" }) })
);Request Inspection
route.request() exposes method, headers, postData. Assert POST body after click via Promise.all with waitForRequest.
page.on("request") logs all traffic—verbose; prefer targeted waitForRequest in assertions.
- HAR recording via recordHar option in config for offline replay
- Block third-party analytics routes to speed tests
- Sync route patterns with OpenAPI paths for maintainability
const requestPromise = page.waitForRequest("**/api/login");
await page.getByRole("button", { name: "Sign in" }).click();
const request = await requestPromise;
expect(request.postDataJSON()).toEqual({ email: "ada@example.com" });APIRequestContext
request fixture from @playwright/test performs API calls sharing cookies with browser context—seed data then verify UI.
Base URL from config applies to request.get("/api/items") paths.
test("shows seeded item", async ({ page, request }) => {
await request.post("/api/items", { data: { name: "Test Item" } });
await page.goto("/items");
await expect(page.getByText("Test Item")).toBeVisible();
});Network Timing
Measure response timing with response.timing() or Performance API in page.evaluate for SLA assertions in synthetic monitoring tests.
Avoid flaky millisecond thresholds—assert order of events or threshold generous with retry.
- Use route.continue to add latency simulating slow network
- Test offline behavior with context.setOffline(true)
- WebSocket mocking requires custom route or library-specific hooks