Playwright WebSocket vs HTTP Route
Playwright WebSocket vs HTTP route: route() intercepts the opening HTTP reply; each later frame needs a proxy. Choose by which exchange the test controls.
BotBrowser Team

Want the structured docs for Getting Started?
This article lives in the editorial library. For step-by-step setup, reference material, and ongoing updates, jump into the docs section.
A Playwright websocket failure often begins with the wrong channel being mocked. An HTTP route can replace the JSON that fills the first dashboard view, while a later WebSocket frame still arrives from another connection and changes the live text. The browser can show both the expected summary and an unexpected update because page.route() and page.routeWebSocket() own different traffic.
BotBrowser can supply an isolated BrowserContext for an authorized test with an owned page, but it does not decide which transport produces a dashboard value or turn a synthetic socket into server-side evidence. The test owner still chooses the route, supplies the frame, and verifies any remote effect outside the browser.
TL;DR
- Inspect the network record before changing the locator or timeout: an HTTP response and a WebSocket frame are different evidence.
page.route()can replace an HTTP request while the WebSocket remains live.page.routeWebSocket()can own a matched socket, but it does not replace an HTTP route for the initial response.- Mock the smallest transport that controls the asserted value; install both only when the page needs both synthetic channels.
- A synthetic frame does not prove durable storage, authorization, or the behavior of a third-party service.
Contents
- Read the transport before the assertion
- The dashboard experiment
- HTTP route: first paint is not the live channel
- WebSocket route: own the connected channel
- Choose the smallest test double
- Keep the synthetic boundary visible
- Practical conclusion
Read the transport before the assertion
The network panel, Playwright's request events, and a WebSocket event answer different questions. A request event identifies a URL, method, and outgoing request. Its response object supplies status, headers, and body. A WebSocket event identifies the connection URL and the frames exchanged over it. A stale live value can be a failed assertion on the page, but the repair starts with the channel: was the page waiting for a response that never arrived, or did a frame arrive from a socket that the test did not control?
Playwright's network mocking guide covers requests and responses. Its WebSocketRoute API is the socket-side contract. The Page routeWebSocket method matches a socket URL and gives the handler a route object; without a server connection, the route can provide the full communication.
That distinction matters in a dashboard because initial data and live data often travel by different routes. A successful JSON response can populate a summary, then a socket can replace a second region with a newer revision. A test that changes only the HTTP route will see the intended summary and the real socket's later value. That is not a flaky locator; it is a partial test double.
The dashboard experiment
The owned local page first calls GET /api/summary and then opens ws://…/live. Both values are visible in the document. Two cases ran in separate BrowserContexts with Playwright 1.58.0 and the currently installed stock Chrome 158.0.8127.37:
| Case | HTTP route | WebSocket route | Summary | Live text | Real socket observed |
|---|---|---|---|---|---|
http-route-only | mocked | not installed | HTTP summary from route | live revision 7 | 1 |
http-route-plus-socket | mocked | mocked | HTTP summary from route | live revision 7 from routeWebSocket | 0 |
In the first case, page.route('**/api/summary') fulfilled the HTTP call and the page recorded http-summary at 17 milliseconds. The live region was still untested at the immediate read; the socket opened and the real frame arrived at 140 milliseconds. In the second case, the same HTTP route produced the summary and page.routeWebSocket('**/live') answered the subscription. The routed live frame arrived at 12 milliseconds, and the test observed no real WebSocket connection.
The experiment changed one transport at a time. The page, viewport, synthetic response and frame content stayed fixed. That makes the result a transport comparison, not a performance claim. The measured times describe this local harness only; the useful observation is which channel supplied each visible value.
One other useful observation is the immediate read. The test captured the DOM before the socket had settled, which showed the HTTP summary but not the later live text. The later checked state used Playwright's retrying value assertion for the HTTP summary and the expected live text instead of a fixed sleep. If the reader expects both fields to be complete at the first read, the assertion should wait for the live state rather than treating the socket delay as a broken HTTP route.
Preserve the event order in the failure receipt. A timestamp on the HTTP text and another on the socket text can show whether the page rendered once or twice. The exact milliseconds belong to the local harness; the ordering belongs to the application contract. A page that writes both values before its ready state is ready has a different contract from one that deliberately streams the second value later.
The page in this fixture uses one same-origin origin for the document, API, and socket. That keeps the route matching easy to inspect. A cross-origin socket would add origin, authentication, and proxy boundaries that this local test does not exercise. Those boundaries belong to the application and network policies, not to a synthetic frame.
The same-origin choice also makes the fixture reproducible without remote credentials. The page server and the socket server share one loopback process, so the HTTP route and the socket route are selected for the same origin. A test that changes only the route pattern would miss a page that moved the socket to another origin.
HTTP route: first paint is not the live channel
An HTTP route is the right tool when the asserted state comes from a request or response. It can return a known JSON summary, exercise an error status, or hold a request open for a readiness test. The page can then assert the summary without waiting for a remote API.
It does not own a socket. The request event and the WebSocket event have different URLs and different frame histories. A real socket can still update the live region even when every HTTP call is synthetic. If the test wants a deterministic live value, it must either disable the socket deliberately or install a socket route that controls the frame.
Use request matching to prove that the intended call was routed. A handler that never receives the request is an observation about the browser path; it does not establish that the response was synthetic. Keep the matched route count beside the visible result so a reviewer can distinguish an exercised route from a coincidental DOM state.
The HTTP mocking article covers the general test-double boundary for owned requests. The remaining question here is transport ownership: an HTTP response can be correct while an independently live socket changes the value after the response returns.
Inspect the response body before asserting a summary. A route can return the correct HTTP status but omit a field, return an unexpected content type, or deliver a schema the page handles differently. A visible summary is the application's interpretation of that response, not the whole response contract. Keep the route match, status, and response class in the receipt.
If the request is made by a worker or a page inside a service worker scope, confirm which BrowserContext and page owns it. A route installed after the request starts may miss it. Install the route before navigation, then assert that the handler was entered. A zero match count with an apparently successful UI is a different diagnosis from a matched synthetic response.
Keep the response direction explicit. A request event can show that the browser asked for the summary, while the response event shows what the page received. The receipt should distinguish an unmatched request from a matched request with an unexpected response. Both can produce a wrong visible summary, but only the second proves that the HTTP route was exercised.
WebSocket route: own the connected channel
page.routeWebSocket() intercepts a matching WebSocket. In its handler, a route can answer messages with ws.send() or call connectToServer() to inspect a real connection. The handler must choose which side it owns. Calling onMessage() on a route stops automatic forwarding for that direction, so a handler that wants passthrough has to forward explicitly.
When the live value is the contract, a socket route can provide the initial frame after subscribe. It can also model a close or a deliberately malformed message. Keep the frame text and schema beside the test, assert the visible live state, and report whether the test saw a real connection or a mocked route.
The socket route does not empty or replace the HTTP summary. It also does not prove the server record was stored. A mock that answers with revision 7 is a local test double; only an approved integration check can show that the server persisted that revision and authorized the request.
Do not infer server behavior from the page's socket event. A real or mocked frame is data delivered to the page. The browser may update a label without making a durable write, and a page may show the same label after a reconnect. The test's receipt should state whether the socket was real or routed and what assertion the page made.
A route that calls connectToServer() needs a different expectation from a fully mocked route. It can observe or modify frames around a real connection, but the server and the test both participate. If the goal is a deterministic offline UI, a fully routed socket is easier to explain. If the goal is to check a real serialization path, an approved integration environment is the stronger evidence.
Inspect the socket URL and frame direction before choosing a handler. A message sent from the page to the route is not the same as a message sent from the route back to the page. If both directions are mocked, record who sent the subscribe frame and who produced the live frame. A single onMessage() call changes the forwarding behavior for one side of the connection.
Choose the smallest test double
| Asserted behavior | Use HTTP route | Use WebSocket route | Evidence it establishes |
|---|---|---|---|
| Initial response renders a known summary | Yes | No | The page handles the synthetic HTTP response |
| A subscribe frame updates the live region | No | Yes | The page handles the synthetic socket frame |
| Summary and live value must agree in one test | Yes | Yes | Both owned channels were exercised in this scenario |
| A real server persisted the new revision | No | No | Requires an approved integration or service observation |
| A third-party dashboard changed its behavior | No | No | Outside an owned test double's authority |
Start with the smallest row that answers the question. If the page needs a fresh summary and a new live revision, install both routes and assert the ordering. If the test only checks the summary, leave the socket live and make the scope explicit, or replace the socket with a documented stub. Do not widen a request route into a catch-all merely because the live text changed.
Use the response-after-click diagnostic when the missing evidence is a request/response pair. Use the networkidle and readiness article when the page is usable but the test waits on the wrong network state. Register the live frame's owner in this article's narrower socket route.
Do not treat a response and a socket frame as interchangeable fixtures. An HTTP mock that returns a summary does not create a live subscription, and a socket mock that sends a revision does not produce the initial JSON response. When a test needs both, install both before navigation and assert each channel's visible outcome independently before checking their combination.
Keep route patterns narrow. A socket URL with a query token may need a predicate that ignores the token while matching the path. A request URL may carry a version or tenant field that belongs to the scenario. Store the exact match rule with the test so a future URL change produces a visible unmatched route instead of a silently broad catch-all.
Use a channel-specific failure message. If the live region is empty while the summary is correct, name the socket route in the failure; if the summary is wrong while the live region updates, name the HTTP route. A shared generic assertion that both values were incorrect hides which channel failed first. Separate route counters and visible targets make the repair local.
Keep the synthetic boundary visible
Give each route a test-only name and a separate receipt. Record the HTTP status or response class, the socket path, whether a route was matched, the visible summary and live text, and cleanup status. Do not retain cookies, authorization headers, full request bodies, or copied production frames.
Run the page in a fresh BrowserContext when cookies, storage, or service workers can affect the socket. Remove the request and socket routes in finally, close the page, and close the context. A clean browser context does not clean a server database, close a real socket, or authorize a third-party simulation.
The reduced fixture remains in docs/evidence/playwright-websocket-mock-versus-http-route-run-20261119.json; it keeps the command, exit status, fixture digest, route matches, event order, visible values, and the distinction between a real socket and the mocked route. The executable source is beside it in docs/evidence/playwright-websocket-mock-versus-http-route-fixture-20261119.cjs.
This run is a stock-Chrome local runner observation, not a BotBrowser capability or performance result. BotBrowser can launch its own executable and profile under Playwright control, but it does not select the transport or make a synthetic frame authoritative for a remote service.
Separate retained evidence from public article text. The local run can record route matches, visible values and event order; the published article explains the transport decision without copying private frames or request bodies.
When a test fails, preserve the first failure before cleanup. A later unroute() or context-close error should not erase the missing frame or HTTP response. Record the route that was expected, whether it matched, the last visible value, and the cleanup outcome as separate fields. That leaves the next reader with a falsifiable cause instead of a generic timeout.
FAQ
Does page.route() also mock a WebSocket?
No. page.route() handles HTTP requests and responses. A WebSocket connection is a separate event and needs page.routeWebSocket() when the test must control its frames.
Does page.routeWebSocket() replace the initial JSON response?
No. The initial dashboard summary can still come from GET /api/summary. A socket route only owns the matching socket; install the HTTP route as well when the asserted state needs both synthetic channels.
Should I wait for both visible values before asserting?
Wait for the exact states the application contract promises. If the live field is asynchronous, wait for that live state rather than assuming the first paint should contain it. Use a visible state transition or Playwright's assertion retry instead of a fixed sleep.
Practical conclusion
Read the transport before changing the test. A summary that comes from an HTTP response and a live value that arrives over a WebSocket need different route APIs. page.route() owns the request; page.routeWebSocket() owns the matched socket. Install the smallest route that controls the asserted value, add the second only when the page needs both synthetic channels, and keep the result labeled as a local test double. The live value is deterministic only when the test actually owns the frame that writes it.
Sources
This article is part of the guide: Browser Automation Getting Started: A First Run Map
Related Articles
Browser Automation Network Mocking for Owned Tests
Getting StartedChrome Remote Debugging Port: What It Exposes
Getting StartedPlaywright Iframe Not Loading? Check the Frame
Getting StartedBrowser Automation Test Fixtures and Isolation
Getting StartedPlaywright Wait for Response After Click: Fix the Race
Getting StartedPlaywright Trace Viewer for Authorized Test Debugging
Run the same check in BotBrowser
Load a profile, keep the signals you just read about consistent inside the browser, and confirm the result on your own machine before a rollout.