Mock an API with page.route
intermediate Network interception Challenge 12 of 22
The shop’s empty-state test depends on the shared staging database being empty, and the error-state test is skipped because there is no way to make staging fail. Use network interception to make both tests deterministic.
The page loads its data from GET /api/products (with optional query parameters).
Requirements
- In both tests, intercept the products API with
page.route(...)beforepage.goto. - Empty state: fulfil with status 200 and a JSON body
{ items: [], total: 0 }, then assert that “No products found” is visible. - Error state: fulfil with status 500, then assert that the
alertshows “Something went wrong. Please try again.”. - Remove the
test.skip().
Expected output
Both tests register a route for the products API before navigating. One fulfils it with `{ items: [], total: 0 }` and asserts the empty state; the other fulfils it with status 500 and asserts the error alert.
Scenarios (3)
Your tests run once against each version of the demo app. They must pass on the working app and fail on every version with a planted bug.
- ○Working app · must pass
- ○Bug: no empty state · must catch
- ○Bug: no error banner · must catch
Checks (5)
- ○Intercepts the API with page.route (or context.route)
- ○Answers the request with route.fulfill({...})
- ○Registers the route before navigating
- ○Returns a JSON body
- ○Simulates a 500 error for the error-state test
Ctrl/⌘ + Enter to run tests · your code is saved in this browser
Results
Run the tests to see results here.
Demo app
The working app. You can click around it; your tests start from a fresh copy.