How to test WebSocket: Playwright and load
WebSocket is tested in Playwright through the websocket event and page.routeWebSocket, while load is measured with k6 or Artillery, not with browsers. The subscription must be made before navigation, and the test waits for an event with a predicate, not for time. A failure is emulated by closing with a code on the server's behalf, then reconnection and catch-up are checked. Load tests measure delivery latency and the reconnect storm.
Networking · Real-time
A chat works in the UI, but how do you check the messages themselves, a drop and 1000 simultaneous clients?
A test presses "Send" and the message appears in the list. That is not enough: it is unknown what actually went through the channel, what happens if the server closes the connection and whether the service survives a thousand connected clients. WebSocket does not fit an ordinary page.route, because it is not a request-response pair. The lesson shows four levels of verification and, for each, which tool serves and what it cannot do.
What to check. The handshake and authentication (rejection without a token), message format and order, idempotency on repeated delivery, UI behaviour on a drop and reconnection, size limit, channel permissions, closing with the right code. The protocol is covered in the lesson on handshake, frames and closing.
Four levels of WebSocket verification
Observation. Playwright emits a websocket event for every connection of the page. It has framesent, framereceived, close and socketerror, and the payload field is a string or a Buffer. The main rule: wait for an event, not for time.
Wait for an event or for a timer
waitForTimeout(2000)
The test waits a fixed time hoping the message has arrived. It fails on slow CI and pointlessly slows down on fast machines.
waitForEvent and web assertions
The test waits for the event or UI state itself and moves on as soon as it happens. It does not depend on machine speed.
// subscribe before navigation, or the connection is missed
const wsPromise = page.waitForEvent('websocket');
await page.goto('/chat');
const ws = await wsPromise;
const reply = ws.waitForEvent('framereceived', {
predicate: (e) => String(e.payload).includes('"type":"message"'),
});
await page.getByRole('textbox').fill('hello');
await page.keyboard.press('Enter');
expect(JSON.parse(String((await reply).payload)).text).toBe('hello');
The websocket event must be subscribed before navigation: the connection opens while the page loads, and whoever subscribes later misses it. The predicate in waitForEvent filters out service frames (heartbeats) so the test does not stop at someone else's message.
Replacement. page.routeWebSocket(url, handler) (since Playwright 1.48) intercepts the connection. Without connectToServer() there is no real server: the test answers itself and no backend is needed. With connectToServer() a proxy is created, in which messages can be peeked at or changed:
await page.routeWebSocket('wss://example.com/ws', (ws) => {
ws.onMessage((message) => {
if (message === 'ping') ws.send('pong');
});
// an event from the "server"
ws.send(JSON.stringify({ type: 'welcome' }));
});
// proxy mode: a real server plus a peek
await page.routeWebSocket(/\/ws$/, (ws) => {
const server = ws.connectToServer();
ws.onMessage((m) => server.send(m));
server.onMessage((m) => ws.send(m));
});
Simulating a failure. A drop is emulated by closing on behalf of the "server" with the required code and checking that the client reconnected and restored its state. Here a connection counter in the closure tells "the client retried" from "the client hung":
let connections = 0;
await page.routeWebSocket('wss://example.com/ws', (ws) => {
connections++;
// the "server" closes the first connection with an error
if (connections === 1) ws.close({ code: 1011, reason: 'boom' });
});
await page.goto('/chat');
// the client must connect a second time
await expect.poll(() => connections).toBe(2);
await expect(page.getByTestId('chat-status')).toHaveText('online');
The test does not call waitForTimeout: expect.poll and web assertions repeat the check until the condition holds. A "messages are not lost" test additionally checks that after reconnecting the client asked for the missed ones by the last id, rather than just opening a new stream.
Load. Playwright is not suitable for this: every browser is heavy, and the goal is thousands of light clients. Use k6 (the k6/websockets module) or Artillery (the ws engine): virtual users following the scenario "connect, subscribe, listen for N seconds".
import { WebSocket } from 'k6/websockets';
import { check } from 'k6';
export const options = { vus: 500, duration: '2m' };
export default function () {
const ws = new WebSocket('wss://example.com/ws');
ws.onopen = () =>
ws.send(JSON.stringify({ type: 'subscribe', channel: 'prices' }));
ws.onmessage = (e) =>
check(JSON.parse(e.data), { 'has type': (m) => m.type !== undefined });
// listen for 30 seconds, then close
setTimeout(() => ws.close(), 30000);
}
Measure the number of simultaneous connections, delivery latency (time from the server event to receipt), the share of connection errors, behaviour on a server restart (a reconnection storm) and memory leaks on a long run. The single number "5000 clients connected" without delivery latency proves nothing.
Limits and alternatives. Replacement via routeWebSocket covers up the real integration: a mock does not know that the message schema changed on the server. So a few end-to-end tests stay without replacement, and the message contract is checked separately. Cloud real-time services and brokers have their own SDKs and tools. For the protocol level (does the server close with a code, does it limit frame size) no browser is needed: a client such as ws in Node is enough, which can send arbitrary frames and headers, something the browser API cannot.
Common mistakes.
- Subscribing to the
websocketevent aftergoto: the connection is already open and the test waits until the timeout. - Asserting the first message received: the channel has heartbeats and other events, a predicate is needed.
- Putting
waitForTimeoutinstead of an event: the test is both slow and unstable. - Measuring load with a Playwright test: the resources go to browsers, not to the server.
- Keeping only the mock: nobody checks the contract with the real server.
Check yourself
A test waiting for framereceived sometimes fails with a timeout although the message appears in the UI. What error do you look for in the code?
Answer
Most likely the websocket subscription happens after goto: the connection is already open and the test did not see it. The subscription (waitForEvent) is created before navigation. A second candidate: ws.waitForEvent('framereceived') is created after the action, and the reply arrived before the subscription. A third: the predicate catches the wrong message, for example a heartbeat.
How do you check that a client reconnects after the server closes the connection with code 1011, without a real backend?
Answer
Through page.routeWebSocket without connectToServer: on the first handler call the "server" does ws.close({ code: 1011 }), and the connection counter in the closure must reach 2 (expect.poll), after which the UI status is checked. No waitForTimeout at all.