Testing WebSocket Connections and Message Flow
WebSocket testing breaks most teams' existing test infrastructure. The stateful, bidirectional nature of WebSocket connections means you can't reuse the same request/response patterns you use for REST APIs. You need to think in terms of connection lifecycle, message sequences, and concurrent state — not individual HTTP calls.
This guide covers how to test WebSocket connections and message flow from the ground up: connection setup, message sending and receiving, ordering guarantees, error handling, and reconnection logic.
What Makes WebSocket Testing Different
HTTP testing is synchronous from the test's perspective: send a request, wait for a response, assert on that response. The connection is ephemeral.
WebSocket testing is asynchronous and stateful:
- The connection persists across multiple message exchanges
- Messages can arrive in any order relative to your test actions
- The server can push messages without the client requesting them
- Connection state (open, closing, closed) affects what operations are valid
- Authentication and authorization often happen at connection time, not per-message
You need test infrastructure that can open connections, send messages, capture responses, and coordinate between concurrent message streams — all without deadlocking or creating race conditions in your tests.
Connection Lifecycle Testing
Before testing message flow, test the connection lifecycle itself.
Basic Connection Establishment
const WebSocket = require('ws');
describe('WebSocket connection lifecycle', () => {
test('establishes connection successfully', (done) => {
const ws = new WebSocket('ws://localhost:3000');
ws.on('open', () => {
expect(ws.readyState).toBe(WebSocket.OPEN);
ws.close();
done();
});
ws.on('error', done);
});
test('connection times out when server unreachable', (done) => {
const ws = new WebSocket('ws://localhost:9999');
ws.on('error', (error) => {
expect(error.code).toBe('ECONNREFUSED');
done();
});
});
test('server sends close frame with correct code', (done) => {
const ws = new WebSocket('ws://localhost:3000');
ws.on('open', () => {
ws.close(1000, 'Normal closure');
});
ws.on('close', (code, reason) => {
expect(code).toBe(1000);
expect(reason.toString()).toBe('Normal closure');
done();
});
});
});Test all four close codes your server might send:
- 1000: Normal closure
- 1001: Going away (server shutting down)
- 1008: Policy violation (auth failure after connect)
- 1011: Internal error
Connection Upgrade Validation
WebSocket connections start as HTTP requests with an Upgrade header. Test that the upgrade succeeds correctly:
const http = require('http');
test('WebSocket upgrade returns 101 Switching Protocols', (done) => {
const options = {
hostname: 'localhost',
port: 3000,
path: '/ws',
method: 'GET',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket',
'Sec-WebSocket-Key': Buffer.from('test-key').toString('base64'),
'Sec-WebSocket-Version': '13',
}
};
const req = http.request(options, (res) => {
expect(res.statusCode).toBe(101);
expect(res.headers.upgrade).toBe('websocket');
done();
});
req.on('error', done);
req.end();
});Also test rejection cases: missing version header, invalid key, wrong path.
Message Flow Testing
Request-Response Pattern
Even though WebSocket is bidirectional, many implementations follow a request-response pattern over the persistent connection. Test these explicitly:
function sendAndReceive(ws, message, timeout = 5000) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Response timeout')), timeout);
ws.once('message', (data) => {
clearTimeout(timer);
resolve(JSON.parse(data));
});
ws.send(JSON.stringify(message));
});
}
describe('message request-response', () => {
let ws;
beforeEach((done) => {
ws = new WebSocket('ws://localhost:3000');
ws.on('open', done);
});
afterEach(() => ws.close());
test('subscribe to channel returns confirmation', async () => {
const response = await sendAndReceive(ws, {
type: 'subscribe',
channel: 'prices',
});
expect(response.type).toBe('subscribed');
expect(response.channel).toBe('prices');
});
test('invalid message type returns error', async () => {
const response = await sendAndReceive(ws, {
type: 'unknown_type',
});
expect(response.type).toBe('error');
expect(response.code).toBe('UNKNOWN_MESSAGE_TYPE');
});
});Collecting Multiple Messages
For server-push scenarios, you need to collect a stream of messages rather than waiting for a single response:
function collectMessages(ws, count, timeout = 5000) {
return new Promise((resolve, reject) => {
const messages = [];
const timer = setTimeout(
() => reject(new Error(`Timeout: collected ${messages.length}/${count}`)),
timeout
);
ws.on('message', (data) => {
messages.push(JSON.parse(data));
if (messages.length >= count) {
clearTimeout(timer);
resolve(messages);
}
});
});
}
test('price feed sends updates at expected frequency', async () => {
const ws = new WebSocket('ws://localhost:3000');
await waitForOpen(ws);
ws.send(JSON.stringify({ type: 'subscribe', channel: 'prices/BTC' }));
const messages = await collectMessages(ws, 3, 10000);
expect(messages).toHaveLength(3);
messages.forEach(msg => {
expect(msg.type).toBe('price_update');
expect(msg.price).toBeGreaterThan(0);
});
// Check ordering: prices should have increasing timestamps
for (let i = 1; i < messages.length; i++) {
expect(messages[i].timestamp).toBeGreaterThan(messages[i-1].timestamp);
}
ws.close();
});Message Ordering Tests
Many WebSocket applications require strict message ordering. Test this explicitly:
test('messages arrive in sent order', async () => {
const ws = new WebSocket('ws://localhost:3000');
await waitForOpen(ws);
const sentOrder = [1, 2, 3, 4, 5];
const received = [];
ws.on('message', (data) => {
received.push(JSON.parse(data).sequence);
});
// Send messages rapidly
for (const seq of sentOrder) {
ws.send(JSON.stringify({ type: 'echo', sequence: seq }));
}
await waitForMessages(ws, 5);
expect(received).toEqual(sentOrder);
ws.close();
});If your server processes messages asynchronously, ordering may not be guaranteed. Test your actual contract — not what you assume.
Binary Message Testing
WebSocket supports both text and binary frames. Test binary message handling if your protocol uses it:
test('sends and receives binary data correctly', (done) => {
const ws = new WebSocket('ws://localhost:3000');
ws.binaryType = 'arraybuffer';
const originalData = new Uint8Array([1, 2, 3, 4, 255]);
ws.on('open', () => {
ws.send(originalData.buffer);
});
ws.on('message', (data) => {
const received = new Uint8Array(data);
expect(Array.from(received)).toEqual(Array.from(originalData));
ws.close();
done();
});
});
test('rejects oversized binary messages', (done) => {
const ws = new WebSocket('ws://localhost:3000');
const oversized = Buffer.alloc(10 * 1024 * 1024); // 10MB
ws.on('open', () => ws.send(oversized));
ws.on('close', (code) => {
expect(code).toBe(1009); // Message too big
done();
});
});Reconnection Logic Testing
Production WebSocket clients need reconnection logic. Test it thoroughly:
class ReconnectingWebSocket {
constructor(url, options = {}) {
this.url = url;
this.maxRetries = options.maxRetries || 5;
this.retryDelay = options.retryDelay || 1000;
this.retries = 0;
this.connect();
}
connect() {
this.ws = new WebSocket(this.url);
this.ws.on('close', () => this.handleClose());
this.ws.on('open', () => { this.retries = 0; });
}
handleClose() {
if (this.retries < this.maxRetries) {
this.retries++;
setTimeout(() => this.connect(), this.retryDelay * this.retries);
}
}
}
describe('reconnection behavior', () => {
test('reconnects after server drops connection', async () => {
const connectAttempts = [];
const mockServer = createMockWebSocketServer();
mockServer.on('connection', (ws, req) => {
connectAttempts.push(Date.now());
if (connectAttempts.length < 3) {
// Drop connection immediately for first 2 attempts
ws.terminate();
}
});
const client = new ReconnectingWebSocket('ws://localhost:3001', {
retryDelay: 100,
});
await waitFor(() => connectAttempts.length >= 3, 5000);
expect(connectAttempts.length).toBe(3);
expect(client.retries).toBe(0); // Reset after successful connect
mockServer.close();
});
test('stops reconnecting after max retries', async () => {
// Server that always refuses
const client = new ReconnectingWebSocket('ws://localhost:9998', {
maxRetries: 3,
retryDelay: 50,
});
await sleep(1000);
expect(client.retries).toBe(3); // Hit the limit
});
});Authentication Testing
WebSocket authentication typically happens at connection time via query parameters, headers, or the first message:
describe('WebSocket authentication', () => {
test('valid token in query param connects successfully', (done) => {
const ws = new WebSocket('ws://localhost:3000?token=valid-jwt-token');
ws.on('open', () => {
expect(ws.readyState).toBe(WebSocket.OPEN);
ws.close();
done();
});
ws.on('error', done);
});
test('missing token returns 401 during upgrade', (done) => {
const ws = new WebSocket('ws://localhost:3000');
ws.on('unexpected-response', (req, res) => {
expect(res.statusCode).toBe(401);
done();
});
});
test('expired token closes with 4001 code', (done) => {
const expiredToken = generateExpiredJWT();
const ws = new WebSocket(`ws://localhost:3000?token=${expiredToken}`);
ws.on('close', (code) => {
expect(code).toBe(4001); // Custom: auth expired
done();
});
});
test('token validated per-message for sensitive operations', async () => {
const ws = new WebSocket('ws://localhost:3000?token=valid-jwt');
await waitForOpen(ws);
// Token revocation should take effect
await revokeToken('valid-jwt');
const response = await sendAndReceive(ws, { type: 'admin_action' });
expect(response.type).toBe('error');
expect(response.code).toBe('TOKEN_REVOKED');
ws.close();
});
});Testing with HelpMeTest
Unit tests with ws cover known scenarios. HelpMeTest adds continuous monitoring for your live WebSocket endpoints:
*** Test Cases ***
WebSocket Connection and Message Flow
[Documentation] Monitor live WebSocket endpoint
Connect To WebSocket wss://api.yourapp.com/ws?token=${AUTH_TOKEN}
WebSocket Connection Should Be Open
Send WebSocket Message {"type": "subscribe", "channel": "updates"}
${response}= Receive WebSocket Message timeout=5s
Should Be Equal ${response}[type] subscribed
WebSocket Should Receive {"type": "update"} within=30s
Close WebSocketRun this as a health check every 60 seconds. If your WebSocket endpoint stops accepting connections or messages stop flowing, you get alerted before users notice.
Common Failure Patterns
The listener leak: Adding ws.on('message', handler) inside a loop or repeated function call stacks listeners. Each connection accumulates handlers from previous runs. Use ws.once('message', handler) for single-response scenarios.
Missing await on connection: Sending messages before the connection is open silently drops them in some implementations. Always await open or check readyState === WebSocket.OPEN before sending.
Test timeout masking slow servers: A 5-second timeout for a response that should arrive in 100ms will pass even when your server is degraded. Set timeouts close to your SLA, not arbitrarily large.
Forgetting to close connections: Each test that doesn't close its WebSocket leaves an open connection. At scale, this exhausts file descriptors and causes tests to fail mysteriously. Always close in afterEach or use a connection pool with cleanup.
Race conditions in message collection: If you start listening for messages after sending a request, you can miss messages that arrive before your listener is attached. Attach listeners before sending.
What to Test
For every WebSocket endpoint, cover at minimum:
- Connection establishment (success and rejection cases)
- Authentication (valid, invalid, expired, revoked)
- Message send and receive for every message type in your protocol
- Error responses for invalid inputs
- Connection close (normal and abnormal)
- Reconnection behavior
- Concurrent connections (does state leak between them?)
- Message ordering (if your protocol guarantees it)
WebSocket connections are long-lived and stateful. A bug in your connection handling can affect every user for the duration of their session, not just a single request. Test accordingly.