Playwright Network Interception

A security checkpoint at an airport inspects every bag before it boards a plane, sometimes allowing it through and sometimes pulling it aside for a closer look. Network interception gives Playwright that same checkpoint power over every request a webpage sends and receives.

The Interception Checkpoint

Page Sends a Network Request
          |
          v
   Playwright Intercepts It
          |
   +------+------+
   |             |
 Allow It    Modify or Block It
   |             |
Real Server   Custom Response Returned

Watching Every Network Request

page.on('request', (request) => {
  console.log(`${request.method()} ${request.url()}`);
});

await page.goto('https://example.com');

This logs every request the page makes while loading, useful for confirming an analytics tracking call actually fires or spotting unexpected calls to third-party services.

Blocking Unwanted Requests

await page.route('**/ads/*', (route) => route.abort());
await page.goto('https://example.com');

This blocks any request matching an advertisement URL pattern before it ever leaves the browser, useful for testing how a page behaves when ad content fails to load.

Mocking an API Response

await page.route('**/api/products', (route) => {
  route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify([
      { id: 1, name: 'Test Sneakers', price: 59.99 },
    ]),
  });
});

await page.goto('https://example.com/shop');

This replaces the real product list with fake, predictable data. The page displays "Test Sneakers" regardless of what the actual backend server would normally return.

Simulating a Server Error

await page.route('**/api/checkout', (route) => {
  route.fulfill({ status: 500, body: 'Internal Server Error' });
});

await page.getByRole('button', { name: 'Place Order' }).click();
await expect(page.getByText('Something went wrong')).toBeVisible();

This forces the checkout request to fail on purpose, confirming the website shows a proper, friendly error message instead of crashing or freezing silently.

Simulating a Slow Network

await page.route('**/api/search', async (route) => {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  await route.continue();
});

This delays a search request by three seconds, useful for confirming a loading spinner actually appears and disappears correctly during slower network conditions.

A Real-World Example

A team wants to test how their checkout page behaves when a payment server times out, a situation difficult to trigger reliably using the real payment provider. Mocking a failed response recreates this exact scenario instantly and consistently, every single time the test runs.

Quick Practice Task

Pick a page with an API-driven list, such as products or articles. Write a test that mocks the API response with fake data and confirms the page displays it correctly.

Key Takeaways

  • Interception can watch, block, modify, or delay network requests.
  • Mocking responses tests specific scenarios without needing a real backend.
  • Simulated errors confirm a page handles failures gracefully.
  • Overusing mocks can hide real integration issues if used carelessly.

Leave a Comment

Your email address will not be published. Required fields are marked *