All challenges · Advanced Techniques

Challenge 21 of 29 · Stretch skills · Advanced Techniques

Mock a GET Request

Intercept a request a page makes on load and answer it with your own data, set up before the page starts, so the page shows a state you control.

Skills you will practise

  • page.route
  • route.fulfill
  • mock data

The concept

Real APIs are slow, change their data and sometimes go down. To test how a page handles a specific state, such as an empty list, a long list or an error, you can intercept its requests and answer them yourself.

page.route(pattern, handler) registers a handler for matching requests. Inside it, route.fulfill() sends back a response you define: a status, headers and a body. The json option sets the body and content type in one go.

Timing matters again. If the page requests data while it loads, the route must be registered before page.goto(). Register it afterwards and the real request has already gone out.

The fragile version

Fragile
await page.goto('/orders');
await page.route('**/api/orders', route => route.fulfill(noOrders));
await expect(page.getByText('No orders yet')).toBeVisible();

Why it breaks: The orders request happened during goto, before the route existed, so the page shows real data and the empty-state assertion fails.

A robust Playwright version

Robust
const noOrders = { status: 200, json: [] };
await page.route('**/api/orders', route => route.fulfill(noOrders));
await page.goto('/orders');
await expect(page.getByText('No orders yet')).toBeVisible();

The mock is in place before the page loads, so the page renders exactly the state under test.

This is a general example on a made-up page, not the challenge’s reference solution.

Common mistakes

  • Registering the route after navigation.
  • A URL pattern that does not match (query strings and hosts trip people up; try a glob like **/api/orders*).
  • Forgetting to call fulfill, continue or abort, which leaves the request hanging.

FAQ

How do I mock an API in Playwright?

await page.route(pattern, r => r.fulfill({ json: data })) before the request is made.

Can I mock an error response?

Yes. Pass status: 500 and a body to route.fulfill().

Does page.route work for requests from service workers?

Not by default when a service worker handles them; see Playwright's serviceWorkers: 'block' option.

Try it

Practise this in Challenge 21. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.

Practise this challenge free