How to Test WebSocket Reconnect Logic, Missed Messages, and Resubscribe Flows Without Flaky Assertions
By Luca Müller · November 15, 2026
A practical guide to testing WebSocket reconnect logic, missed messages, and resubscribe flows in web apps, with deterministic assertions and reproducible failure simulation.
WebSocket failures are rarely just transport failures. A reconnect can succeed at the socket layer and still leave the app stale, unsubscribed, duplicated, or out of order. That is why the real target is not “did the socket reconnect?” but “did the app recover its live state correctly after the reconnect?”
If you need to test websocket reconnect logic, the safest approach is to separate three concerns:
- Transport behavior, did the connection close and reopen?
- Session behavior, did the client authenticate, resubscribe, or replay state?
- UI behavior, did the user see the right messages, counts, or indicators after recovery?
That separation is what keeps reconnect tests from becoming flaky. A test that waits for “the next message” without controlling server timing will eventually fail for the wrong reason. A better test creates a deterministic disconnect, controls message delivery, and asserts on a stable end state instead of timing-sensitive intermediates.
What you are actually testing
A WebSocket reconnect flow usually contains at least one of these paths:
- The browser loses the socket and the client retries with backoff.
- The server closes the connection and expects the client to reconnect.
- The client reconnects but must reauthenticate or refresh a token.
- The client reconnects and must resubscribe to channels, rooms, symbols, or document streams.
- The app must recover missed messages, either by replay, cursor, sequence number, or a fresh state fetch.
If your test only checks that
onopenfired again, it has not validated recovery. It has only validated transport restoration.
The browser WebSocket API is defined by the WHATWG WebSockets specification, and the baseline protocol comes from RFC 6455. Those documents explain the connection model, but they do not tell you how your app should replay missed events or resubscribe. That logic belongs to your application, which is why your test strategy has to be app-aware.
Use a deterministic failure model, not a real network accident
Random packet loss, manual tab refreshes, and ad hoc Wi-Fi toggling are poor test inputs. They make failures hard to reproduce and impossible to diagnose cleanly.
Instead, pick one of these controlled approaches:
- Server-side close frame: close the socket intentionally from a test server.
- Proxy interruption: cut the TCP path or block upgrade traffic in a controllable layer.
- Test double server: run a local WebSocket server that can delay, drop, or reorder messages on command.
- Application hook: expose a test-only control path that simulates reconnect events or message replay gaps.
For browser automation, a local test server is usually the most readable option because it keeps the network behavior explicit and repeatable.
Minimal test server idea
This server sends a sequence number with each event, then closes the connection at a chosen point so the client must reconnect and catch up.
import { WebSocketServer } from 'ws';
let seq = 0; const history = [];
const wss = new WebSocketServer({ port: 8081 });
wss.on(‘connection’, (ws) => { ws.send(JSON.stringify({ type: ‘hello’, lastSeq: seq }));
const interval = setInterval(() => {
seq += 1;
const msg = JSON.stringify({ type: ‘update’, seq, value: msg-${seq} });
history.push(msg);
ws.send(msg);
if (seq === 3) {
ws.close(1006, 'forced reconnect');
clearInterval(interval);
} }, 200); });
The useful part here is not the exact server code, it is the presence of a stable sequence number. Once you have that, you can assert on gaps, duplicates, and replay behavior without guessing whether a missing message was caused by timing or a real bug.
Assert on state, not on transient socket events
A reconnect test becomes flaky when it asserts on a momentary UI state that may appear and disappear between animation frames. Prefer the final observable outcome.
Good assertions:
- The reconnect banner disappears after recovery.
- The user is rejoined to the expected room or symbol stream.
- The latest visible message has the expected sequence number.
- Missed messages were replayed once, not duplicated.
- The app does not show stale presence, unread count, or chart data.
Risky assertions:
- “The socket reopened within 300 ms” unless you control timing tightly.
- “The reconnect spinner appeared” unless that spinner is the actual product requirement.
- “A specific console message was logged” unless logs are part of the contract.
A practical rule is to assert the app’s externally visible contract, not its implementation detail.
A Playwright pattern that keeps reconnect tests stable
Playwright is a good fit for browser-level reconnect coverage because you can watch app behavior while still driving the page like a user. The Playwright network docs are useful when you need to wait for a specific response or inspect traffic, but for WebSockets you often get better results by instrumenting the app with a small test hook.
For example, expose the current live state on window in test builds only:
// app test hook, shipped only in non-production builds
window.__realtimeState = {
connected: false,
lastSeq: 0,
subscriptions: []
};
Then test the recovery outcome:
import { test, expect } from '@playwright/test';
test('reconnects and replays missed messages', async ({ page }) => {
await page.goto('http://localhost:3000');
await expect.poll(() => page.evaluate(() => window.__realtimeState.connected)).toBe(true);
await expect.poll(() => page.evaluate(() => window.__realtimeState.lastSeq)).toBeGreaterThanOrEqual(3);
await expect.poll(() => page.evaluate(() => window.__realtimeState.subscriptions)).toContain('room-42');
});
Why this is less flaky than DOM-only polling, the app state gives you one stable source of truth. You are not trying to infer reconnect success from incidental text or CSS transitions.
How to test missed messages without brittle timing
Missed message testing is really ordering and reconciliation testing. The app should recover a gap using one of these mechanisms:
- replay from the last seen sequence number,
- fetch current snapshot on reconnect,
- resubscribe and receive a fresh server state,
- reconcile local optimistic updates against authoritative state.
The important distinction is this:
- Reconnect means the transport is back.
- Resubscribe means the client asked the server for the right live feed again.
- Replay means the client recovered events it missed while offline.
Do not mix those assertions together. Test each one separately, then add one integration test that confirms the whole chain.
A useful strategy is to send three numbered events, close the socket after event 2, then reconnect and send event 3 plus a replay of event 2 if your app is designed to de-duplicate. Your test should verify exactly one copy of each logical event.
If your product uses event IDs, make that the assertion key. If it uses sequence numbers, assert on continuity. If it uses timestamps, be careful, timestamps are often too coarse to distinguish replay from duplicate delivery.
Test the resubscribe handshake explicitly
Resubscribe bugs are easy to miss because the socket may reconnect cleanly while the app listens to nothing.
Typical failure modes:
- the reconnect path reopens the socket but never re-sends subscription messages,
- the app restores UI state but not server-side subscription state,
- a token refresh happens after reconnect, but the subscribe call used the old token,
- duplicate subscribe messages cause duplicate streams or double-counting.
A robust resubscribe test checks that the client sends the expected subscribe command after reconnect and that the server acknowledges it before messages resume.
Example of a simple client contract:
{ “type”: “subscribe”, “channel”: “room-42”, “cursor”: 128 }
After reconnect, your assertion should verify both that the subscribe message was reissued and that the resumed stream begins at the expected cursor or sequence.
Distinguish transport bugs from app-state bugs
This distinction matters because the fix path is different.
- If the socket never reconnects, look at backoff, heartbeat, close codes, auth refresh, and browser compatibility.
- If the socket reconnects but the UI is stale, look at subscription restoration, cache invalidation, and event reconciliation.
- If messages are duplicated, look at idempotency, deduplication keys, and replay handling.
- If the UI shows a brief inconsistency and then recovers, decide whether that flash is acceptable product behavior or a bug.
A test suite should make those layers visible. One way is to keep one transport-focused test, one protocol-focused test, and one UI-focused test instead of one oversized end-to-end case that is hard to diagnose.
A compact decision table for reconnect coverage
| Test layer | What it proves | Best assertion style | Typical failure it catches |
|---|---|---|---|
| Transport | Socket closes and reopens | Connection flags, close/open events | Backoff, auth, browser-specific disconnect handling |
| Protocol | Client resubscribes correctly | Outgoing subscribe frames, cursor replay | Lost subscriptions, stale tokens, duplicate joins |
| Data recovery | Missed messages are reconciled | Sequence continuity, deduped event IDs | Gaps, duplicates, stale snapshots |
| UI | User sees the correct live state | Final rendered state, unread count, banner dismissal | Stale counters, wrong room, lingering offline state |
Use the narrowest layer that proves the behavior you care about. If the bug report says “messages stop after reconnect,” you usually do not need to prove browser socket internals in the same test.
CI setup that reduces false failures
Real-time tests are especially sensitive to environment noise, so isolate them in CI.
Recommended guardrails:
- run them against a local or containerized WebSocket server,
- avoid shared test data between parallel jobs unless each test has its own channel or room ID,
- use explicit test IDs or channels so one job cannot consume another job’s messages,
- add timeout budgets that reflect the protocol, not an arbitrary global default,
- keep reconnect tests separate from broad smoke flows if they fail for different reasons.
If your test runner supports retries, use them carefully. A retry can hide a true recovery bug if the second run passes because the server state changed. Retries are most useful for isolated infrastructure noise, not for protocol logic.
When to add more coverage, and when to stop
Add more cases if your product depends on real-time continuity, for example chat, trading, collaborative editing, monitoring dashboards, or incident tools. Those apps are vulnerable to subtle reconnect bugs because state can drift quietly.
Stop adding cases when additional scenarios no longer exercise a new failure mode. A fourth test that only changes the label from “room” to “channel” is not more coverage, it is duplicated maintenance.
A good minimum set is usually:
- clean reconnect after a forced close,
- reconnect with one missed message and replay,
- reconnect with resubscribe and auth refresh,
- duplicate-prevention check for replayed events.
That set is small enough to maintain and broad enough to catch the bugs that matter.
FAQ
How do I simulate a WebSocket disconnect in browser tests?
Use a controlled server close, a local proxy interruption, or a test server that intentionally closes the connection. Avoid relying on random network instability.
Should I assert on WebSocket events or on the UI?
Both, but at different layers. Use socket events for transport and protocol checks, then assert on final UI state for user-visible recovery.
How do I test missed messages after reconnect?
Give events sequence numbers or IDs, force a disconnect, then verify the client either replays or fetches the missing state without duplicates.
What is the difference between reconnect and resubscribe?
Reconnect restores the socket transport. Resubscribe restores the app’s live data subscriptions after the transport comes back.
Why do reconnect tests become flaky?
They usually depend on uncontrolled timing, incidental UI states, or real network noise. Make the failure deterministic and assert on stable end-state data instead.