page.route: stub the backend
Why This Matters
Some screens are hard to reach with real data. How does the shop look with no products at all? With a product whose name is far too long? On the real site you would have to change the database to find out. With page.route the test decides what the browser gets back, so any state is one line away, in every run, on every machine.
How it works
page.route(pattern, handler) intercepts every request from the page whose URL matches the pattern. The handler decides what happens:
| In the handler | Effect |
|---|---|
route.fulfill({ json }) | Answer with your own response; the server is never called |
route.fetch() then route.fulfill({ response, json }) | Call the real server, change its answer, pass it on |
route.continue({ headers }) | Let the request through, optionally changed |
route.abort() | Let the request fail, as if the network broke |
route.fallback() | Leave this request to the next matching route |
Register routes before the page makes the request, so before page.goto. A route lives as long as the page, so it never leaks into another test.
An empty shop
The shop loads its products from /api/shop/products. Answer with an empty list and the page has to show its empty state:
const PRODUCTS = "**/api/shop/products**";
test("an empty result shows the empty state", async ({ page }) => {
await page.route(PRODUCTS, (route) =>
route.fulfill({
json: { items: [], page: 1, limit: 6, total: 0, totalPages: 0, priceRange: { min: 0, max: 0 } },
}),
);
await page.goto("/shopping");
await expect(page.getByText("No products found matching your criteria.")).toBeVisible();
await expect(page.getByTestId("results-count")).toHaveText("0");
});
The stub has the same shape as the real response (lesson 18’s ProductListSchema). A stub the frontend cannot read tests nothing but your typing.
** in the pattern matches anything, including the query string the page adds (?page=1&limit=6&sort=name&order=asc).
Change a real response
Sometimes you want real data with one difference. route.fetch() makes the real call; you change the body and pass it on:
test("a real response, changed on the way", async ({ page }) => {
await page.route(PRODUCTS, async (route) => {
const response = await route.fetch(); // the real API call
const body = await response.json();
body.items[0].name = "Changed by the test";
await route.fulfill({ response, json: body });
});
await page.goto("/shopping");
await expect(page.getByTestId(/^product-\d+$/).first()).toContainText("Changed by the test");
});
This keeps everything else realistic: prices, stock, images, the number of products.
Real run
Both tests are in tests/module-5/network.spec.ts. In the real run each took about 3.7 seconds, and both passed first time.
When not to mock
A mocked test proves the frontend handles a response correctly. It proves nothing about the backend: if the real API changes its shape, the mocked test stays green. Keep both kinds: API tests (module 4) for the contract, and mocked UI tests for the states that are hard to reach.
Exercise
Write a test that makes the first product look like it is on sale: take the real response, set onSale: true and lower price below originalPrice. Check that the card shows a SALE badge.
Show suggested solution
test("a product on sale shows the badge", async ({ page }) => {
await page.route(PRODUCTS, async (route) => {
const response = await route.fetch();
const body = await response.json();
Object.assign(body.items[0], { onSale: true, price: 9.99 });
await route.fulfill({ response, json: body });
});
await page.goto("/shopping");
await expect(page.getByTestId(/^product-\d+$/).first()).toContainText("SALE");
});
The real shop has one product on sale, the Ergonomic Chair. A test that relies on it breaks the day that sale ends. With the route the test makes its own sale on the first card, and no longer depends on the shop’s data or its sort order.