Intercepting requests with page.route()

Why mock?

A real backend rarely gives you an empty list, a 500 error, a 10-second delay or a dropped connection when you need one. With page.route() your test decides what the browser receives, so those states can be tested on demand and every run gets the same result.

The four things a route handler can do

  • route.fulfill(): answer with your own response. The request never reaches the server.
  • route.abort(): fail the request as if the network dropped.
  • route.continue(): send it on to the server, optionally changing the URL, method, headers or body.
  • route.fetch(): get the real response, so you can change it before fulfilling.

Register the route before the request happens

await page.route('**/api/products', (route) =>
  route.fulfill({
    json: { products: [{ id: 99, name: 'Mock Product', price: 1 }] },
  })
);

await page.goto('/network/mocking');
await page.getByRole('button', { name: 'Load Products' }).click();
await expect(page.getByRole('cell', { name: 'Mock Product' })).toBeVisible();

{ json } sets the body and the Content-Type header for you. Use { status: 500 } to simulate a server error.

Change a real response

await page.route('**/api/products?*', async (route) => {
  const response = await route.fetch();
  const body = await response.json();

  body.products.push({ id: 100, name: 'Injected Product', price: 1 });

  await route.fulfill({ response, json: body });
});

The real server answered, so the status, headers and the other products are real. You changed only what the test needs.

Fail only the first time

await page.route(
  '**/api/notifications',
  (route) => route.fulfill({ status: 503 }),
  { times: 1 }
);

After one use the route removes itself and later requests reach the real server. That makes retry buttons easy to test. page.unroute() removes a route by hand.

Matching requests

  • Glob patterns match the whole URL: '**/api/products' does not match /api/products?search=mo.
  • For query strings use a regular expression such as /\/api\/products\?search=/, or check new URL(route.request().url()).searchParams inside the handler and call route.fallback() for requests you do not want to handle.
  • page.route() applies to one page. context.route() also covers popups and new tabs.

Record and replay

page.routeFromHAR(path, { update: true }) records real traffic to a HAR file. Run it again without update and every matching request is served from that file. That gives you a realistic, offline backend.

Mocks prove that the UI handles a response correctly. They do not prove the real API returns that response. Pair them with API tests (see the API Testing page).

Products API

The application requests products from the API. Playwright can intercept this request and return a custom response.

Product Search

Sends the search term as a query string, for example /api/products?search=mo.

Notifications

Shows an error with a retry button when the request fails.