Exit course
Chapter 7 of 9 Intermediate 8 min read 3 quick checks Updated

Mocking APIs with page.route

On this page
  1. Find out what the page calls
  2. Replace a response
  3. Modify a real response
  4. Break it on purpose
  5. When to mock and when not to

So far every test talked to the real API. Sometimes that is exactly wrong for a UI test: you want to see the empty state, the error message, or a product with a 200-character name, and the real API will not produce those on demand. page.route() lets a test intercept the requests the browser makes and answer them itself. This chapter covers the three things you will do with it: replace a response, modify a real one, and break one on purpose. It ends with when not to mock.

Find out what the page calls#

Before you can mock a request you need to know what it looks like. Log the page's requests once, or open the network tab of a trace (chapter 5 of the Playwright course). For the Toolshop's home page and search, the API calls include:

QUERY https://api.practicesoftwaretesting.com/products
GET https://api.practicesoftwaretesting.com/brands
GET https://api.practicesoftwaretesting.com/categories/tree
QUERY https://api.practicesoftwaretesting.com/products/search

Two surprises worth spotting before you write a route. First, the product list and the search are sent with the HTTP QUERY method, not GET. Second, these requests carry their parameters in the body, not the URL. The curl and request.get('/products/search', { params }) calls in earlier chapters used GET with a query string, which the API also accepts, but the browser does it differently. A route pattern copied from your API tests, such as '**/products?page=*', would never match what the browser sends. Always check what the page itself requests.

Replace a response#

Create tests/ui/mocking.spec.ts:

import { test, expect } from '@playwright/test';
import { ProductPageSchema } from '../../lib/schemas';
import type { Page, Product } from '../../lib/types';

test('empty search results, served by a mock', async ({ page }) => {
  // parse() keeps the mock honest: it must match the real API's shape
  const empty = ProductPageSchema.parse({
    current_page: 1, last_page: 1, per_page: 9, total: 0, data: [],
  });
  await page.route('**/products/search*', (route) => route.fulfill({ json: empty }));

  await page.goto('/');
  await expect(page.getByTestId('product-name').first()).toBeVisible(); // app is ready
  await page.getByTestId('search-query').fill('pliers');
  await page.getByTestId('search-submit').click();

  await expect(page.getByTestId('no-results')).toHaveText('There are no products found.');
});

Step by step:

  • Register the route before the page makes the request. Routes apply from the moment you add them; a route added after goto() misses everything the page loaded on the way in.
  • '**/products/search*' is a glob matched against the full URL. ** matches any characters including /, and the trailing * covers a query string if there is one.
  • route.fulfill({ json }) answers with status 200, a JSON body and Content-Type: application/json, without the request ever leaving the browser.
  • The schema from chapter 5 checks the mock. The real search has pliers in it, so the only way to see the empty state is to fake it, but a fake that does not match the real API tests a situation that cannot happen. Running the mock body through ProductPageSchema.parse() means a mock that drifts from the real shape fails loudly.
  • The "app is ready" line waits for the first product card before typing into the search box. Typing into an input before a single-page app has finished starting up is a classic source of rare, hard-to-reproduce failures; waiting for something the app renders after start-up removes the race.

Your route page.route('**/api/items?page=*', ...) never fires, although the page clearly loads items from /api/items. What is the most likely cause?

Routes intercept any method in every browser, and globs work fine. A route that never fires almost always means the URL the browser really requests differs from the pattern, or the request happened before the route existed. Log the page's requests and compare.

Modify a real response#

Often you want the real data with one detail changed: a long name, a sold-out flag, a price of zero. route.fetch() sends the request to the real server and gives you the response to edit:

test('a real response with one field changed', async ({ page }) => {
  await page.route(
    (url) => url.pathname === '/products',
    async (route) => {
      const response = await route.fetch();
      const body: Page<Product> = await response.json();
      body.data[0].name = 'Mocked Hammer';
      await route.fulfill({ response, json: body });
    },
  );

  await page.goto('/');

  await expect(page.getByTestId('product-name').first()).toHaveText('Mocked Hammer');
});
  • A function as the matcher. url.pathname === '/products' matches the product list exactly, regardless of method or query string, and does not also catch /products/search. A predicate is clearer than a glob whenever the URL has variants you need to tell apart.
  • route.fulfill({ response, json }) keeps the real status and headers and swaps in your body.

Because the rest of the data is real, this kind of test also notices when the real API changes in a way the page cannot handle, which a fully mocked test never will.

Break it on purpose#

Error handling is the code path real APIs exercise least in testing, because you cannot ask a healthy server to fail. A route can:

test('a failing search looks like an empty one', async ({ page }) => {
  await page.route('**/products/search*', (route) =>
    route.fulfill({ status: 500, json: { message: 'Server Error' } }),
  );

  await page.goto('/');
  await expect(page.getByTestId('product-name').first()).toBeVisible(); // app is ready
  await page.getByTestId('search-query').fill('pliers');
  await page.getByTestId('search-submit').click();

  // The shop reports a server error as "no products": worth a product decision.
  await expect(page.getByTestId('no-results')).toHaveText('There are no products found.');
});
Running 3 tests using 3 workers

  ✓  3 [chromium] › tests/ui/mocking.spec.ts:20:1 › a real response with one field changed (3.1s)
  ✓  1 [chromium] › tests/ui/mocking.spec.ts:5:1 › empty search results, served by a mock (3.4s)
  ✓  2 [chromium] › tests/ui/mocking.spec.ts:36:1 › a failing search looks like an empty one (7.2s)

  3 passed (7.8s)

This test documents something you only learn by breaking the API: when search fails with a 500, the Toolshop tells the user "There are no products found." A customer cannot tell "nothing matches" from "search is down", and will likely leave instead of retrying. Whether that is acceptable is a product decision, but it is exactly the kind of behaviour that mocked failure tests are for. If the team decides an error message should appear, this test changes to expect it, and then guards it.

Other failures worth simulating the same way: a 401 in the middle of a session (does the app send the user to login?), a slow response (does a spinner appear, is the button disabled against double submits?), and route.abort() for a network failure.

A test registers page.route('**/api/orders', ...) to return a fake order, then calls page.request.get('/api/orders') to check it. It gets the real orders. Why?

Routing applies to the browser's own network traffic. API clients send their requests directly, which is why they are the right tool to check the real server and the wrong tool to check a mock. A quick test confirms it: with a search route in place, page.request still returns the real search results.

When to mock and when not to#

Mocking trades realism for control. A mocked UI test is fast, deterministic and can reach states the real system rarely produces. It also tests nothing on the server and keeps passing after the real API changes, unless you check the mock against a schema as above.

A workable split for most suites:

  • API tests (chapters 1 to 5) hit the real API and check the contract.
  • UI tests with API setup (chapter 4) use the real API end to end for the main flows.
  • Mocked UI tests cover what the real API cannot produce on demand: empty, error, slow and extreme-data states.

If a mocked test is the only test of a flow, that flow is untested against the real server. And if you find yourself recording large real responses into fixtures to replay, look at page.routeFromHAR(), which replays a recorded HAR file; the same caveat about drifting from the real API applies even more strongly there.

The checkout UI tests all mock the payment API. The backend renames amount to total, the front end breaks in production, and every test stayed green. What would have caught it?

Mocks return whatever you wrote, so they cannot notice a real API change. A schema check against the real endpoint, or at least one test that uses the real API, is what detects the rename.

You now have API tests, UI tests that use the API for setup, and mocked UI tests. The last chapter runs all of them in CI and puts the browser tests on a cloud grid.