Notes
How it works
Here is how it works. When the page makes a request, the browser checks whether the test registered a route for that URL. If not, the request goes to the real API. If so, your handler decides: fulfil it with a fake response, continue it, perhaps with changes, fetch the real response and modify it, or abort it to simulate a network failure. The page cannot tell the difference.
- the page calls fetch()
- the browser asks Playwright: any route for this URL?
- no → request goes to the API
- yes → your handler decides: fulfill (fake response) continue (maybe changed) fetch + modify the real one abort (network failure)
Empty state
First, the empty state. Register a route for the products API that fulfils with a count of zero and no items. Register routes before the page loads, then go to the home page. ShopRung showed no products match your search, and zero products. With real data, the shop always has twelve products, so without mocking this state would never be tested until a real customer met it.
await page.route(
"**/api/products?*", route =>
route.fulfill({ json:
{ count: 0, items: [] } }));
await page.goto("/");
await expect(page.getByTestId(
"no-results")).toBeVisible();
saw: "No products match your
search." and "0 products" Server error
Next, a server error. Fulfil with status five hundred and an error body whose message says database unavailable. ShopRung showed that message in its error area, with no crash and no blank page. You can check every error your API documents this way: four oh one sends the user to log in, four oh nine shows the conflict, five hundred shows a friendly message.
route.fulfill({
status: 500,
json: { error: "internal",
message: "Database
unavailable" } })
expect(getByTestId("error"))
.toBeVisible()
saw: "Database unavailable"
no crash, no blank page Modify the real one
Often you want real data with one odd value. Fetch the real response inside the route, change one field, here the first product's name becomes one hundred and twenty letters, and fulfil with the modified body. Everything else stays real. Now you can check the card layout with a very long name, prices with many digits, or a missing optional field, all without touching the database.
await page.route("**/api/products?*",
async route => {
const response = await route.fetch();
const body = await response.json();
body.items[0].name = "A".repeat(120);
await route.fulfill(
{ response, json: body });
});
checks layout with a 120-char
name, all else real Offline
Finally, abort the request as if the internet disconnected. ShopRung showed the text failed to fetch. That is the browser's raw technical error, shown directly to a shopper. It is not a crash, but it is a usability issue worth raising: a message like you seem to be offline, try again, with a retry button, would be better. Mocking found it in seconds.
route.abort("internetdisconnected")
ShopRung showed:
"Failed to fetch"
the raw browser error, shown
to a shopper
→ worth raising: say "You
seem to be offline. Try
again." with a retry Patterns
Routing details. URLs can be glob patterns, like any path containing api slash products with a query, or regular expressions. Page route covers one page; context route covers every page and popup in the context. Inside a handler, read the request's method, to mock only posts, for example. Unroute removes a route. And route from HAR replays a recorded HAR file of real traffic, a quick way to run UI tests without a backend.
"**/api/products?*" glob
/\/api\/orders\/\d+$/ regex
page.route(...) this page
context.route(...) all pages
route.request().method()
→ mock only POSTs
page.unroute(url)
page.routeFromHAR("shop.har")
replay recorded traffic Other tools
Other tools. Cypress has intercept, which matches a method and URL and returns a fixture body, very similar in spirit. Selenium four is adding network interception through WebDriver BiDi, though the APIs are newer and vary by language. A common Selenium approach is still to point the app at a mock server, like WireMock from Part four, through a configurable API address.
// Cypress
cy.intercept("GET",
"/api/products*",
{ body: { count: 0, items: [] } })
// Selenium 4 (BiDi network
// interception, newer APIs)
// or a proxy / WireMock behind
// a configurable API URL When not to mock
Know when not to mock. Mock to test UI states: empty, errors, slowness and odd data. Do not mock the happy path of critical journeys like checkout, or you only test the front end against your own imagination. Keep fakes realistic by copying real responses and checking them with schemas or contract tests from Part four. And keep a few full end to end tests against the real API.
- mock to test UI STATES: empty, errors, slow, odd data
- do not mock the happy path of critical journeys
- keep fakes realistic: copy real responses, use schemas or contract tests (Part 4)
- a few full end-to-end tests must hit the real API
Common mistakes
Mocking mistakes. Registering a route after the page has already sent the request, so the mock never applies. URL patterns so broad they catch requests you did not mean to mock. Fake responses that drift away from the real API. Mocking the happy path of checkout so the real integration is never tested. And forgetting to set status codes, so an error body arrives with two hundred.
- registering routes AFTER goto (request already sent)
- patterns too broad (mock everything by accident)
- fakes that drift from the real API
- mocking the happy path of checkout
- forgetting status codes
Say it like this
In the interview: I use network interception. With Playwright's page route I fulfil empty lists, server errors and odd data, modify real responses, or abort requests to simulate going offline, always registering routes before navigation. I keep fakes close to real responses, backed by schemas or contracts, and leave the main journeys unmocked in a small set of end to end tests.
- "With network interception: page.route fulfils empty lists, 500s and odd data, modifies
- real responses, or aborts to simulate offline, registered
- before navigation. I keep
- fakes close to real responses
- and leave critical journeys
- unmocked in a few E2E tests."