Skip to content

Network Testing

Playwright exposes full network visibility — listen to requests, stub responses, record HAR files, and assert UI reacts correctly to API success and failure.

Observing Network Traffic

Register listeners with page.on('request') and page.on('response') for logging or assertions. For control, use page.route() to intercept and fulfill or modify responses.

Combine waitForResponse with UI actions to synchronize tests with API completion without arbitrary delays.

page.on('response', res => {
  if (res.url().includes('/api/')) console.log(res.status(), res.url());
});

const resPromise = page.waitForResponse('**/api/products');
await page.getByRole('button', { name: 'Load' }).click();
expect((await resPromise).ok()).toBeTruthy();

Logging helps debug; route mocking helps determinism.

Network APIs

page.on('request' | 'response' | 'requestfailed')
page.waitForResponse(url | predicate)
page.route(url, handler)
context.route(url, handler)  // all pages in context
  • Route handlers run before request hits network (if fulfilled).
  • Continue with route.continue() to passthrough with modifications.
  • Abort with route.abort() to simulate offline.
  • HAR recording via recordHar in context options.

Network Testing Reference

Listen, wait, or mock.

Goal API
Log API calls page.on('response')
Wait for fetch waitForResponse('**/api/x')
Mock JSON page.route + route.fulfill
Slow API route.fulfill after delay
Offline mode context.setOffline(true)
Record HAR recordHar: { path: 'test.har' }

Offline and Error Simulation

await context.setOffline(true);
await page.getByRole('button', { name: 'Sync' }).click();
await expect(page.getByText('You are offline')).toBeVisible();

Listening for requestfinished

page.on('requestfinished', req => ...) fires after responses complete — useful for counting API calls without stubbing them.

Common Mistakes

  • Hitting real production APIs in every test run.
  • Not awaiting waitForResponse before assertions.
  • Route pattern too broad, breaking unrelated requests.
  • Forgetting to unregister routes leaking into next test (use beforeEach).

Key Takeaways

  • Network listeners aid debugging; routes aid determinism.
  • waitForResponse ties UI tests to API timing.
  • Mock external services; keep contract tests separate.
  • Offline mode tests resilience paths.

Pro Tip

Log failing API responses in CI with page.on('response', r => { if (r.status() >= 400) ...}) — speeds root cause vs generic timeout.