Network Interception and Mocking
Relevant source files
The following files were used as context for generating this wiki page:
Playwright provides powerful capabilities to intercept, inspect, and modify network requests made by a page. This feature is essential for testing various network conditions, mocking backend responses, and isolating the front-end from backend services. By routing network traffic, developers can create stable and predictable tests that are not dependent on live services, test edge cases like network failures, or modify requests on the fly to test different application states.
The core of this functionality lies in the page.route() and browserContext.route() methods, which allow developers to register a handler for network requests that match a specific URL pattern. Within the handler, one can decide to continue the request, fulfill it with a mock response, modify it before it goes to the network, or abort it entirely. This system is also integrated with HAR (HTTP Archive) files, enabling tests to be run against recorded network traffic.
Sources: README.md, packages/playwright/types/test.d.ts
Core API and Architecture
The primary entry point for network interception is the route method, available on both Page and BrowserContext objects. This method registers a callback function that is executed for each request matching the provided URL pattern.
Sources: packages/playwright/types/test.d.ts:4020-4029
Key Methods
| Method | Description |
|---|---|
page.route(url, handler) | Registers a request handler for the specific page. |
browserContext.route(url, handler) | Registers a request handler for all pages within the context. |
page.unroute(url, handler) | Removes a previously registered route handler. |
page.routeFromHAR(har, options) | Fulfills requests based on a provided HAR file. |
Sources: packages/playwright/types/test.d.ts:4020-4029, 4070-4076, 4103-4109, tests/library/browsercontext-har.spec.ts:25-27
Interception Flow
The following diagram illustrates the sequence of events when a network request is made from a page with an active route handler.
This diagram shows how a user-defined handler can intercept a request and choose to either mock it with fulfill, let it proceed (potentially modified) with continue or fallback, or block it with abort.
Sources: packages/playwright/types/test.d.ts:4030-4068
URL Matching
Playwright provides flexible URL matching options, including strings, regular expressions, and glob patterns. This allows for precise targeting of requests to be intercepted.
| Pattern Type | Example | Description |
|---|---|---|
| String | 'https://example.com/api/data' | Exact string match. |
| RegExp | /api\/v\d+\/data/ | Matches URLs against a regular expression. |
| Glob | '**/*.{png,jpg,jpeg}' | Matches URLs using glob-like patterns. |
Sources: tests/page/interception.spec.ts:37-93, packages/playwright/types/test.d.ts:4021-4023
Glob Patterns
Glob patterns offer a powerful way to match URLs. The conversion from a glob string to a regular expression is handled internally.
Key glob pattern features include:
*: Matches any character except/zero or more times.**: Matches any character zero or more times.{a,b}: Matches eitheraorb.?: In a URL, this is treated as a query string separator, not a wildcard, unless escaped.
The following test cases from the codebase demonstrate how glob patterns are interpreted:
**/*.jsmatcheshttps://localhost:8080/foo.jsbut nothttps://localhost:8080/foo.css.**/{a,b}.jsmatches.../a.jsand.../b.jsbut not.../c.js.**/*.{png,jpg,jpeg}matches image files with the specified extensions.**/api\?parammatches a URL with a query parameter namedparam.
Sources: tests/page/interception.spec.ts:37-93
Handling Intercepted Requests
Once a request is intercepted, the Route object passed to the handler provides methods to control its outcome.
| Method | Description |
|---|---|
route.abort([errorCode]) | Aborts the request. errorCode is optional. |
route.continue([overrides]) | Continues the request with optional modifications to headers, method, postData, etc. |
route.fulfill([options]) | Fulfills the request with a mock response. |
route.fallback([overrides]) | Continues the request with modifications, but falls back to other handlers if available. |
Sources: packages/playwright/types/test.d.ts:4030-4068
Fulfilling Requests
The route.fulfill() method is used to provide a mock response, bypassing the actual network request.
fulfill Options:
| Option | Type | Description |
|---|---|---|
status | number | Response status code, e.g., 200 or 404. |
headers | Object | An object with response headers. |
body | string | Buffer | Response body. |
json | any | A serializable object to be sent as a JSON response. Content-Type is set to application/json. |
path | string | Path to a file to be used as the response body. |
contentType | string | The Content-Type header value. |
Sources: packages/playwright/types/test.d.ts:4043-4068
An example from the test suite shows how to fulfill a request:
// tests/page/interception.spec.ts:20-27
await page.route('**/foo', route => {
const slash = route.request().url().lastIndexOf('/');
const name = route.request().url().substring(slash + 1);
void route.fulfill({
status: 200,
contentType: 'text/css',
body: 'responseFromInterception:' + name
});
});
Modifying Requests
The route.continue() and route.fallback() methods allow for modifying the request before it is sent to the server. This is useful for adding headers, changing the request method, or altering post data.
continue and fallback Overrides:
| Option | Type | Description |
|---|---|---|
url | string | If specified, the request will be issued to the new URL. |
method | string | If specified, the request will be issued with the new method. |
headers | Object | If specified, the new headers will be used. |
postData | string | Buffer | If specified, the new data will be sent with a POST request. |
Sources: packages/playwright/types/test.d.ts:4030-4041, tests/library/har.spec.ts:258-273
Interaction with Service Workers
Network interception in Playwright interacts with service workers. A route handler installed on a page is applied after the service worker's fetch event handler has had a chance to process the request. This means if a service worker responds to a request, the page's route handler will not be triggered for that request.
However, if the service worker decides to pass the request to the network (e.g., by calling fetch()), the page's route handler will then intercept it.
This behavior is demonstrated in tests/page/interception.spec.ts:
- A service worker is registered that responds to requests for
**/foo. - A
page.route()handler is set up for**/foo. - When the page fetches
foo, the service worker responds first, and the interception handler is not called. - For a request to
passthrough, which the service worker does not handle, the interception handler is called.
Sources: tests/page/interception.spec.ts:29-57, tests/page/page-event-request.spec.ts:44-121
HAR-based Mocking
Playwright can use a HTTP Archive (HAR) file to mock network responses, which is extremely useful for creating tests based on recorded network traffic.
routeFromHAR
The browserContext.routeFromHAR() method sets up routing for all pages in the context to serve responses from a .har file.
The flow for this functionality is as follows:
This diagram shows that when routeFromHAR is active, Playwright attempts to find a matching entry in the HAR file. If found, it fulfills the request from the recording. If not, its behavior depends on the notFound option.
Sources: tests/library/browsercontext-har.spec.ts, packages/playwright/types/test.d.ts:4103-4109
Recording HAR files
To create a HAR file, you can use the recordHar option when creating a new browser context. This will record all network traffic for pages in that context into the specified file.
// Example of HAR recording configuration
const context = await browser.newContext({
recordHar: {
path: 'test.har',
mode: 'full', // 'full', 'minimal', or 'omit'
content: 'attach' // 'attach', 'embed', or 'omit'
}
});
Sources: tests/library/har.spec.ts:25-29, packages/playwright/types/test.d.ts:6021-6040
Summary
Network interception and mocking are fundamental features in Playwright for creating robust, reliable, and comprehensive end-to-end tests. By providing fine-grained control over network traffic through page.route(), developers can simulate various backend states and network conditions without relying on live services. The integration with HAR files further enhances this capability by allowing tests to run against pre-recorded network sessions, ensuring consistency and speed. Understanding how interception interacts with browser features like service workers is key to leveraging its full potential.