NashTech Blog

Mastering Network Interception in Playwright: Mocking, Modifying, and Testing Edge Cases

Table of Contents
intercept-and-mock-api-requests-in-playwright

One of Playwright’s standout capabilities is its powerful network interception system. Without relying on a live backend, you can intercept HTTP requests, return mock payloads, simulate 500 Internal Server Errors, or emulate network delays.

Using network mocking helps you build test suites that are faster, more resilient, and capable of covering tricky edge cases like server meltdowns or slow network connections, that are otherwise difficult to reproduce on demand.

The Gateway to Interception: page.route

The page.route(url, handler) method registers a handler executed every time a network request matches a given URL pattern. Inside the handler, you decide how to route the request:

await page.route('**/api/products', async route => {
  // 3 primary options:
  // route.fulfill()  → Serve a mock response WITHOUT contacting the real server
  // route.continue() → Let the request pass through (with optional modifications)
  // route.abort()    → Cancel the request (simulate a network failure)
});

1. Mocking API Responses

The most common use case for network mocking is serving mock data so you can test UI behavior independently of the backend.

test('displays product list correctly', async ({ page }) => {
  // Register the route rule BEFORE navigating
  await page.route('**/api/products', async route => {
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify([
        { id: 1, name: 'iPhone 16', price: 25000000 },
        { id: 2, name: 'iPad Pro', price: 30000000 },
      ]),
    });
  });

  await page.goto('/shop');
  await expect(page.getByRole('listitem')).toHaveCount(2);
  await expect(page.getByText('iPhone 16')).toBeVisible();
});

Pro Tip: Always register your routes before calling page.goto(). Otherwise, initial page requests might fire before your handlers are attached.

Serving Data directly from JSON Fixtures

To keep your test suites clean, you can stream mock data directly from a static file:

await page.route('**/api/products', route =>
  route.fulfill({ path: 'fixtures/products.json' })
);

2. Simulating Errors and Edge States

Network mocking shines when testing boundary conditions that are painful to trigger in staging or production environments.

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

// 2. Simulate complete connection drop
await page.route('**/api/**', route => route.abort('failed'));

// 3. Simulate empty responses (Test "Empty States")
await page.route('**/api/orders', route =>
  route.fulfill({ status: 200, body: '[]' })
);

// 4. Simulate 401 Unauthorized (Test redirect/logout logic)
await page.route('**/api/me', route => route.fulfill({ status: 401 }));

Here is a full test case verifying error handling UI:

test('displays error message when server fails', async ({ page }) => {
  await page.route('**/api/checkout', r => r.fulfill({ status: 500 }));
  
  await page.goto('/checkout');
  await page.getByRole('button', { name: 'Checkout' }).click();
  
  await expect(page.getByText('An error occurred, please try again')).toBeVisible();
});

3. Modifying Real Requests and Responses

Sometimes you don’t want to completely replace the backend; you just need to inspect or modify live traffic on the fly.

Modifying Outgoing Requests

Add custom headers or tweak body parameters before forwarding a request to the server:

await page.route('**/api/search', async route => {
  const headers = { ...route.request().headers(), 'x-test': '1' };
  await route.continue({ headers });
});

Fetch the actual server response, mutate its payload, and return it to your web client:

Patching Live Responses

await page.route('**/api/user', async route => {
  const response = await route.fetch(); // Call the live backend
  const json = await response.json();
  
  json.role = 'admin'; // Override permissions for testing purposes
  
  await route.fulfill({ response, json });
});

4. Route Scope: page.route vs. context.route

  • page.route: Applies only to network requests made inside a specific tab or page instance.
  • context.route: Applies globally across all pages and popups within the browser context.
// Block analytics or advertising network-wide across all pages
await context.route('**/api/analytics', route => route.abort());

// Apply page-specific interception rules
await page.route('**/api/x', handler);

Using context.route inside setup fixtures is a clean strategy for blocking noise (tracking scripts or ad networks) globally across your test suite.

5. Unrouting and Retries

You can remove interceptors dynamically or conditionally run mocking logic to emulate temporary failures.

// Remove a registered route rule
await page.unroute('**/api/products');

// Emulate a temporary server error that succeeds on retry
let count = 0;
await page.route('**/api/data', route => {
  count++;
  if (count === 1) {
    return route.fulfill({ status: 500 });
  }
  return route.continue();
});

6. Asserting Requests Without Interception

If you want to verify that an API call was triggered correctly without intercepting or altering the response, use waitForRequest:

const reqPromise = page.waitForRequest('**/api/track');

await page.getByRole('button', { name: 'Buy Now' }).click();

const req = await reqPromise;
expect(req.method()).toBe('POST');
expect(req.postDataJSON()).toMatchObject({ event: 'purchase' });

7. Recording and Replaying Traffic with HAR Files

Playwright can record network traffic to HTTP Archive (HAR) files and play it back later. This approach turns unpredictable external API dependencies into static, deterministic test fixtures.

// Step 1: Record live traffic into a HAR file (run once to update)
await page.routeFromHAR('hars/shop.har', { url: '**/api/**', update: true });

// Step 2: Replay responses locally from the HAR file (no real network calls)
await page.routeFromHAR('hars/shop.har', { url: '**/api/**' });

8. When to Mock

Use CaseStrategy
UI Components & Frontend LogicMock liberally. Keeps tests fast, stable, and independent of backend uptime.
Edge Cases & Error ScenariosMock liberally. Easily trigger hard to reproduce scenarios like 500 status codes or offline states.
End-to-End IntegrationDo NOT mock. Test real database contracts and network pipelines across full system bounds.

Summary

Playwright’s network interception capabilities eliminate the friction of testing against flaky or incomplete backends. By using page.route, you gain granular control over every HTTP request allowing you to mock responses, modify live data, and simulate rare edge cases in seconds. While heavy mocking keeps your test suite fast and deterministic, always balance it with a few unmocked E2E tests to ensure your frontend and backend seamlessly connect in production.

Picture of Huyen Pham Thu

Huyen Pham Thu

Suggested Article

Scroll to Top