Playwright 17 ๐ญ Network Interception โ route() and mocking API responses
Playwright can intercept every HTTP request a page makes and decide what happens to it: let it continue to the server, modify it, redirect it, fulfill it with a synthetic response, or abort it entirely. The page.route() API provides this control, enabling tests to mock API responses without a running backend, simulate failures and slow networks, inject edge-case data, and verify that the application handles each scenario correctly. Network interception turns tests from dependent on external services into self-contained scenarios with deterministic outcomes.
This chapter covers the route() API in depth: how to register and remove routes, how to fulfill responses with custom status codes, headers, and JSON bodies, how to modify outgoing requests and incoming responses, how to simulate failures and timeouts, and how to combine routing with waitForResponse for request verification. It also covers common patterns such as mocking REST endpoints, throttling responses, and recording real responses for replay. By the end, you will be able to replace any network dependency with a controlled mock and test the application’s behavior under every condition you can imagine.
Key point: page.route() intercepts requests before they leave the browser, letting you fulfill them with synthetic responses, modify real ones, or abort them. Every dependency on a live server becomes a controllable input to your test.
Why network interception exists
The external dependency problem. A test that depends on a live backend inherits every problem the backend has: downtime, slow responses, rate limits, data that changes between runs, and environments that differ from production. When the staging API returns a 500, the test failsโnot because the frontend broke, but because the dependency did. Network interception severs this coupling: the test supplies the response, so the frontend’s behavior is the only variable.
The unreachable state problem. Applications handle states that are difficult to reproduce against a real server: network timeouts, 500 errors, empty datasets, malformed JSON, expired tokens, and slow loading. Triggering these conditions organically requires either a special backend mode or manual intervention. With route(), a test can return a 500 for one endpoint, delay a response by five seconds, or deliver an empty arrayโall in a few lines of code. Every error path becomes testable.
The observation problem. Verifying that the frontend sends the correct requestโthe right URL, the right headers, the right bodyโrequires seeing the outgoing request. Network interception exposes the request object before it is sent, letting tests assert on payloads, capture request counts, and confirm that debouncing or caching works. Without interception, this verification requires a proxy or a backend that logs requests, adding infrastructure that tests should not need.
a. Registering routes and fulfilling responses
The page.route() method accepts a URL pattern and a handler function. The handler receives a Route object and the Request, and must call exactly one of route.fulfill(), route.continue(), route.abort(), route.fallback(), or route.fetch(). A route that handles a request without resolving it leaves the request pending until the test times out.
import { test, expect } from '@playwright/test';
test('mocking a successful API response', async ({ page }) => {
// Intercept any request matching the pattern before the page navigates
await page.route('**/api/users', async (route) => {
// Fulfill with a synthetic response; no server is contacted
await route.fulfill({
status: 200, // HTTP status code
contentType: 'application/json', // response content type
body: JSON.stringify([ // serialized response body
{ id: 1, name: 'Alice', role: 'admin' },
{ id: 2, name: 'Bob', role: 'viewer' },
]),
});
});
await page.goto('/users');
// The application renders the mocked data as if it came from the server
await expect(page.getByText('Alice')).toBeVisible();
await expect(page.getByText('Bob')).toBeVisible();
});
The URL pattern supports glob syntax (**/api/*), regular expressions (/\/api\/users\/\d+/), and predicate functions. Glob patterns are anchored: **/api/users matches any URL ending in that path regardless of protocol or host. A pattern without a wildcard prefix, such as 'api/users', matches relative to the base URL. Routes are matched in reverse registration order, so the most recently registered route winsโuseful for overriding a general mock with a specific one inside a single test.
test('overriding a general mock with a specific one', async ({ page }) => {
// Register the general handler first
await page.route('**/api/**', (route) =>
route.fulfill({ status: 200, body: '{"data":[]}' })
);
// Register the specific handler second; it takes precedence for /api/orders
await page.route('**/api/orders', (route) =>
route.fulfill({
status: 200,
body: JSON.stringify([{ orderId: 'A-100', total: 42.5 }]),
})
);
await page.goto('/dashboard');
// Requests to /api/orders hit the specific mock; all others hit the general one
});
b. Modifying requests and responses with continue() and fetch()
Not every test wants to replace the response entirely. Sometimes the goal is to observe a real request, modify one header, or alter the response body after the server has produced it. The route.continue() method forwards the request to the server, optionally with overrides. The route.fetch() method performs the request programmatically and returns the response, which the handler can then modify and fulfill.
test('adding an authentication header to outgoing requests', async ({ page }) => {
await page.route('**/api/**', async (route) => {
// Forward the request to the server with a modified header
await route.continue({
headers: {
...route.request().headers(), // preserve existing headers
authorization: 'Bearer test-token-123', // inject the test token
},
});
});
await page.goto('/profile');
// The server receives the injected token; the app behaves as authenticated
});
test('modifying a real response before it reaches the app', async ({ page }) => {
await page.route('**/api/products', async (route) => {
// Fetch the real response from the server
const response = await route.fetch();
// Parse the real body and alter one field
const body = await response.json();
body.products[0].price = 0; // force the first product to be free
// Fulfill with the modified body, preserving the original status and headers
await route.fulfill({ response, json: body });
});
await page.goto('/products');
await expect(page.getByText('$0.00').first()).toBeVisible();
});
The route.fulfill({ response }) shorthand reuses the original response’s status, headers, and content type, overriding only the fields provided. This patternโfetch the real response, mutate it, fulfill with the mutationโpreserves server correctness for everything except the field under test, which is often exactly what a test wants. It also lets you inspect real payloads while developing mocks, since the fetched response is available in the handler.
c. Simulating failures, delays, and aborts
The route.abort() method cancels the request as if the network failed. The error code passed to abort() determines the browser’s view of the failure: 'failed' for a generic network error, 'timedout' for a timeout, 'connectionrefused', 'internetdisconnected', and others. To simulate a slow server, the handler can delay before fulfilling; the delay suspends the response while the page’s loading state remains visible.
test('rendering an error state when the API returns 500', async ({ page }) => {
await page.route('**/api/orders', (route) =>
route.fulfill({ status: 500, body: 'Internal Server Error' })
);
await page.goto('/orders');
// The app's error boundary or fallback UI should appear
await expect(page.getByText('Something went wrong')).toBeVisible();
});
test('simulating a network failure', async ({ page }) => {
await page.route('**/api/orders', (route) => route.abort('failed'));
await page.goto('/orders');
await expect(page.getByText('Network error')).toBeVisible();
});
test('simulating a slow response to test loading states', async ({ page }) => {
await page.route('**/api/orders', async (route) => {
// Wait 3 seconds before fulfilling
await new Promise((resolve) => setTimeout(resolve, 3000));
await route.fulfill({
status: 200,
body: JSON.stringify([{ orderId: 'A-100', total: 42.5 }]),
});
});
await page.goto('/orders');
// The loading spinner is visible while the response is pending
await expect(page.getByRole('progressbar')).toBeVisible();
// After the delay, the data appears and the spinner disappears
await expect(page.getByText('A-100')).toBeVisible();
await expect(page.getByRole('progressbar')).toBeHidden();
});
When a request is aborted, the application’s fetch or XMLHttpRequest rejects with a network error, which is the same code path a real offline scenario triggers. When a request is fulfilled with a 500 status, the application’s error handling for non-2xx responses runs. These are different branches of the frontend code, and testing both confirms that each has a user-visible outcome. Neither scenario requires any backend configuration.
Complete Example Session
// ============================================
// PART 1: IMPORT AND TEST SETUP
// ============================================
import { test, expect } from '@playwright/test';
// ============================================
// PART 2: MOCKING A SUCCESSFUL LIST RESPONSE
// ============================================
test('dashboard shows mocked orders', async ({ page }) => {
// Intercept the orders endpoint and return a fixed payload
await page.route('**/api/orders', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 'ORD-001', status: 'shipped', total: 99.0 },
{ id: 'ORD-002', status: 'pending', total: 14.5 },
]),
})
);
await page.goto('/dashboard');
// ============================================
// PART 3: ASSERTING ON THE MOCKED DATA
// ============================================
await expect(page.getByText('ORD-001')).toBeVisible();
await expect(page.getByText('ORD-002')).toBeVisible();
await expect(page.getByText('shipped')).toBeVisible();
// ============================================
// PART 4: CAPTURING THE OUTGOING REQUEST
// ============================================
let requestUrl = '';
await page.route('**/api/orders', (route) => {
requestUrl = route.request().url(); // record the URL
return route.continue(); // let it reach the server
});
// ============================================
// PART 5: TRIGGERING THE REQUEST VIA UI
// ============================================
await page.getByRole('button', { name: 'Refresh' }).click();
// ============================================
// PART 6: VERIFYING THE REQUEST SHAPE
// ============================================
expect(requestUrl).toContain('/api/orders');
// ============================================
// PART 7: MOCKING A DIFFERENT STATUS CODE
// ============================================
await page.route('**/api/orders', (route) =>
route.fulfill({ status: 403, body: 'Forbidden' })
);
// ============================================
// PART 8: RELOADING TO TRIGGER THE ERROR PATH
// ============================================
await page.reload();
await expect(page.getByText('Access denied')).toBeVisible();
// ============================================
// PART 9: SIMULATING A DELAYED RESPONSE
// ============================================
await page.route('**/api/orders', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 2000)); // 2s delay
await route.fulfill({ status: 200, body: '[]' }); // empty list
});
// ============================================
// PART 10: ASSERTING ON THE EMPTY STATE
// ============================================
await page.reload();
await expect(page.getByText('No orders yet')).toBeVisible();
});
The ten parts above progress from a simple static mock through request capture, status-code manipulation, and delayed responses. The same endpoint is mocked three times with different outcomesโsuccess, forbidden, and emptyโdemonstrating that the route handler can be re-registered inside a test to exercise multiple application states against a single page.
Quick Reference
The Route Handler Actions
| Method | Effect | Returns |
|---|---|---|
route.fulfill() | Return a synthetic response | Promise<void> |
route.continue() | Forward to server, optionally modified | Promise<void> |
route.abort() | Cancel the request | Promise<void> |
route.fetch() | Fetch the real response for inspection | Promise<APIResponse> |
route.fallback() | Defer to the next matching route | Promise<void> |
The fulfill() Options
| Option | Purpose | Example |
|---|---|---|
status | HTTP status code | status: 404 |
body | Response body as string | body: 'Not found' |
json | Response body as JSON | json: { data: [] } |
contentType | Content-Type header | contentType: 'application/json' |
headers | Additional headers | headers: { 'x-test': '1' } |
response | Reuse an APIResponse | response: realResponse |
The abort() Error Codes
| Code | Browser Sees | Typical Use |
|---|---|---|
'failed' | Generic network failure | Offline simulation |
'timedout' | Request timed out | Slow network |
'connectionrefused' | Connection refused | Server down |
'internetdisconnected' | No internet | Airplane mode |
URL Pattern Types
| Pattern | Matches | Example |
|---|---|---|
| Glob | **/api/* | **/api/users |
| Regex | /\/api\/users\/\d+/ | new RegExp('/api/users/\\d+') |
| Predicate | (url) => url.endsWith('/api') | Function returning boolean |
| Relative | 'api/users' | Relative to base URL |
Best Practices
โ Do This:
// Register routes before page.goto() so no request escapes
await page.route('**/api/**', handler); // โ
await page.goto('/dashboard');
// Use json: for JSON bodies instead of manual JSON.stringify
await route.fulfill({ status: 200, json: { items: [] } }); // โ
// Use route.fetch() to modify real responses rather than reconstructing them
const response = await route.fetch(); // โ
await route.fulfill({ response, json: mutate(await response.json()) });
// Capture requests to verify outgoing payloads
let captured: Record<string, unknown>;
await page.route('**/api/orders', (route) => {
captured = route.request().postDataJSON(); // โ
return route.continue();
});
// Abort requests you don't care about to speed up tests
await page.route('**/analytics/**', (route) => route.abort()); // โ
// Test each error path with its own route and assertion
await page.route('**/api/orders', (r) => r.fulfill({ status: 500 })); // โ
await expect(page.getByText('Something went wrong')).toBeVisible();
โ Don’t Do This:
// Don't forget to handle the route; unresolved requests hang
await page.route('**/api/**', async () => {}); // โ request never resolves
// Don't call fulfill twice; only the first call takes effect
await route.fulfill({ status: 200 }); // โ
await route.fulfill({ status: 500 }); // โ unreachable, ignored
// Don't use route() for requests already made by the page
await page.goto('/dashboard'); // โ requests already sent
await page.route('**/api/orders', handler); // โ too late
// Don't mock a response without asserting the app renders it
await page.route('**/api/orders', mockHandler); // โ no verification
await page.goto('/dashboard');
// Don't use page.route() when you want browser-wide mocking
await page.route('**/api/**', handler); // โ popups won't be intercepted
// use context.route() for popups and new pages
// Don't rely on the order of parallel requests
await page.route('**/api/a', ...); // โ registration order decides precedence
await page.route('**/api/**', ...); // โ this catches /api/a if registered first
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Mock not applied | Route registered after navigation | Register before goto() |
| Request hangs | Handler never resolves the route | Call fulfill, continue, or abort |
| Wrong mock wins | Most recently registered route takes precedence | Register general routes first, specific last |
| Popup not mocked | page.route() scopes to one page | Use context.route() for all pages |
| Request body unreadable | Reading body after continue() | Read postDataJSON() before forwarding |
| Real server still called | Pattern does not match URL | Test pattern with a console.log(route.request().url()) |
| CORS errors with mocks | Missing access-control-allow-origin header | Add CORS headers to the fulfilled response |
Real-World Examples
1. Mocking a login endpoint
await page.route('**/api/login', (route) =>
route.fulfill({ status: 200, json: { token: 'fake-jwt-token' } })
);
2. Simulating an expired session
await page.route('**/api/session', (route) =>
route.fulfill({ status: 401, body: 'Unauthorized' })
);
3. Mocking a paginated list
await page.route('**/api/items?page=2', (route) =>
route.fulfill({ json: { items: [{ id: 3 }], hasMore: false } })
);
4. Delaying one endpoint to test suspense
await page.route('**/api/slow', async (route) => {
await new Promise((r) => setTimeout(r, 1500));
await route.fulfill({ json: { ok: true } });
});
5. Injecting a server error on a form submit
await page.route('**/api/submit', (route) =>
route.fulfill({ status: 500, json: { error: 'Server error' } })
);
6. Blocking third-party analytics requests
await page.route('**/analytics/**', (route) => route.abort());
7. Counting how many times an endpoint is called
let calls = 0;
await page.route('**/api/search', (route) => {
calls++;
return route.continue();
});
8. Overriding a single field in a real response
await page.route('**/api/profile', async (route) => {
const response = await route.fetch();
const body = await response.json();
await route.fulfill({ response, json: { ...body, verified: true } });
});
9. Mocking a GraphQL endpoint
await page.route('**/graphql', (route) =>
route.fulfill({ json: { data: { viewer: { name: 'Test' } } } })
);
10. Simulating a timeout
await page.route('**/api/orders', (route) => route.abort('timedout'));
Visual
The Request Interception Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ REQUEST LIFECYCLE WITH route() โ
โ โ
โ App calls fetch('/api/orders') โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Playwright intercepts the request โ โ
โ โ Matches against registered route patterns โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โโโโบ fulfill() โโโบ synthetic response โ
โ โโโโบ continue() โโโบ real server โโโบ responseโ
โ โโโโบ abort() โโโบ network error โ
โ โโโโบ fetch() โโโบ real server โ
โ + inspect + mutate โ
โ + fulfill modified โ
โ โ โ
โ โผ โ
โ Response reaches the application โ
โ The app cannot tell whether it was mocked โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Route Registration Order
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ REVERSE REGISTRATION PRECEDENCE โ
โ โ
โ Registered 1st: '**/api/**' โโโบ general โ
โ Registered 2nd: '**/api/orders' โโโบ specific โ
โ โ
โ Request: /api/orders โ
โ โ โ
โ โผ โ
โ Check 2nd route: matches '**/api/orders' โ โ
โ โ โ
โ โผ โ
โ Handler for specific route runs โ
โ (The general route never fires) โ
โ โ
โ Request: /api/users โ
โ โ โ
โ โผ โ
โ Check 2nd route: no match โ โ
โ Check 1st route: matches '**/api/**' โ โ
โ โ โ
โ โผ โ
โ Handler for general route runs โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Mocking Matrix
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WHAT TO MOCK FOR EACH SCENARIO โ
โ โ
โ Scenario Route Action Assert โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ Happy path fulfill(200, data) data visible โ
โ Empty state fulfill(200, []) empty messageโ
โ Server error fulfill(500) error UI โ
โ Unauthorized fulfill(401) login screen โ
โ Forbidden fulfill(403) access deniedโ
โ Slow network delay + fulfill spinner โ
โ Offline abort('failed') retry UI โ
โ Timeout abort('timedout') timeout UI โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Primary method | page.route(pattern, handler) |
| Scope | Per page; context.route() for all pages |
| Handler actions | fulfill, continue, abort, fetch, fallback |
| Precedence | Last registered route wins |
| URL patterns | Glob, regex, predicate, relative |
| Fulfill body | body (string) or json (object) |
| Response reuse | fulfill({ response }) from route.fetch() |
| Abort codes | 'failed', 'timedout', 'connectionrefused', 'internetdisconnected' |
| Unroute | page.unroute(pattern, handler?) |
| Timing | Register before navigation |
Key takeaways:
- Mock before navigation. A route registered after
page.goto()misses the initial requests. Register every mock before the page loads, or usecontext.route()for tests that navigate across multiple pages. - Every handler must resolve the route.
fulfill,continue,abort, orfetchโone of them must be called. A handler that returns without resolving leaves the request pending and the test hanging until timeout. - Reverse registration order matters. The most recently registered matching route runs first. Register broad catch-all routes first and specific overrides later so the specific ones take precedence.
route.fetch()preserves realism. When only one field needs to change, fetch the real response and modify it. This keeps headers, status codes, and unaffected fields accurate without hardcoding a full payload.- Error paths are the highest-value mocks. A 500, a 401, a timeout, and an empty list are often the scenarios that break in production. They are also the easiest to test with
route()because no backend setup is required. - Abort codes simulate distinct network conditions.
'failed','timedout', and'connectionrefused'reach the application through different error paths. Choose the code that matches the scenario being tested. - Verify outgoing requests with captured data. Store
route.request().postDataJSON()orroute.request().headers()in a variable, then assert after the action. This confirms the frontend sends what the backend expects.
Remember: Network interception is the mechanism that makes frontend tests independent of backend availability and data. Every external call becomes a switch the test controls: return success, return failure, delay, abort, or mutate. The application code does not changeโit still calls fetch, still parses JSON, still renders loading and error statesโbut the test decides what comes back and can therefore verify every branch of the frontend’s behavior. Register routes before navigation, always resolve them, and mock both the happy path and the failures; a test suite that only mocks success verifies only half the application.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!