Skip to content

Lesson 6 of 9 · 27m

Network Mocking and Interception at the Right Layer

Use Playwright route interception for boundary simulation, understand what it cannot mock, and avoid turning tests into implementation puppetry.

Network mocking is where good intentions go to become false confidence. I have seen suites 'pass' because the mock still implemented an API contract that the backend deleted three months earlier. Mocking is powerful when you control failure modes and third-party boundaries. It is dangerous when you use it to avoid testing your own server.

Mock boundaries, not your primary system under test

If the test claims to validate your application end to end, your own API should usually be real. Good mock candidates are third-party payment providers, email delivery, CAPTCHA verification, object storage callbacks, analytics beacons, IP geolocation, and partner webhooks.

await page.route('**/api/payments/webhook', async route => {
  await route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify({ received: true }),
  });
});

But ask where the request originates. page.route intercepts browser traffic from that page or context. A backend-to-backend webhook never passes through the browser, so Playwright cannot intercept it there. For those paths, use a mock server, service virtualization, or a test-only backend adapter.

Interception can fulfill, continue, or observe

Playwright routing supports three broad modes:

await page.route('**/api/recommendations', async route => {
  if (new URL(route.request().url()).searchParams.get('mode') === 'empty') {
    return route.fulfill({ json: { items: [] } });
  }
  return route.continue();
});

You can simulate empty states, validation failures, latency, malformed payloads, and server errors. These are useful because real dependencies rarely fail in clean binary ways.

Do not leave sleeps in production test paths merely to imitate slowness everywhere. Use latency when latency is the behavior under test.

Match narrowly or you will mock too much

A broad pattern like **/api/** is a trap. It can swallow authentication, feature flags, and unrelated mutations, producing a frontend that appears healthy while half the system is fictional. Prefer exact host and path matching, such as https://api.stripe.com/v1/payment_intents, rather than broad API wildcards. Also remember service workers. If the application has a service worker cache, requests may never reach the network in the way you expect. Context routing still sees many browser requests, but cache semantics can complicate both observation and response freshness. Disable or control service workers when the test is not about offline behavior.

Contract-drift is the hidden cost

A handwritten mock rots. Reduce drift by generating responses from OpenAPI schemas, TypeScript types, or recorded golden contracts that are reviewed when the dependency changes. For critical third parties, keep one smoke path against the real sandbox. Mocks prove your reaction to a documented response. Sandboxes prove the response still exists.

Record evidence at the network layer

Even when not mocking, network observation can make debugging concrete. Do not turn this into noisy assertions on every analytics call. Use it for diagnostic breadcrumbs or for exact requests central to the workflow.

Field notes

  • page.route does not intercept your backend's outbound HTTP calls. Browser interception and server virtualization are different layers.
  • Mock failures that real users see: timeout, 429, malformed JSON, empty success, partial data, and slow responses.
  • If tests depend on exact ordering of asynchronous requests, the application may be racing; a mock can reveal but not fix that race.
  • Be careful with redirects. Intercepting the first URL may not intercept the redirect target.
  • Never use mocks to hide authentication complexity in a test whose purpose is authentication.

Was this lesson helpful?

Sign in to rate