Testing WebSocket Connections with Jest and ws
WebSocket connections introduce a class of testing challenges that HTTP endpoints don't have: persistent connections, bidirectional messaging, connection lifecycle events, and timing-sensitive behavior. Most developers reach for Jest because it's already in their stack — but writing reliable WebSocket tests in Jest requires a few non-obvious patterns. This post covers them from the ground up.
Why WebSocket Testing Is Different
With REST APIs, a test is simple: send a request, assert the response. WebSockets are stateful. A single connection can send and receive dozens of messages over its lifetime. You need to test:
- That the connection establishes successfully
- That specific messages trigger the right responses
- That the server handles disconnects gracefully
- That reconnection logic works
- That you don't leave open connections (which causes Jest to hang)
Setting Up the Test Environment
Install the dependencies:
npm install --save-dev jest wsFor TypeScript projects:
npm install --save-dev @types/wsA minimal WebSocket server to test against:
// server.js
const { WebSocketServer } = require('ws');
function createServer(port) {
const wss = new WebSocketServer({ port });
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const msg = JSON.parse(data.toString());
if (msg.type === 'ping') {
ws.send(JSON.stringify({ type: 'pong', id: msg.id }));
}
if (msg.type === 'subscribe') {
ws.send(JSON.stringify({ type: 'subscribed', channel: msg.channel }));
}
});
ws.send(JSON.stringify({ type: 'welcome' }));
});
return wss;
}
module.exports = { createServer };The Core Testing Pattern
The key insight for testing WebSockets in Jest: wrap message receipt in a Promise, and use jest.setTimeout generously.
// websocket.test.js
const { WebSocket } = require('ws');
const { createServer } = require('./server');
let server;
let port = 9876;
beforeAll((done) => {
server = createServer(port);
server.on('listening', done);
});
afterAll((done) => {
server.close(done);
});
function connectAndWaitForMessage(url, predicate) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(url);
const timeout = setTimeout(() => {
ws.close();
reject(new Error('Timeout waiting for message'));
}, 5000);
ws.on('message', (data) => {
const msg = JSON.parse(data.toString());
if (predicate(msg)) {
clearTimeout(timeout);
ws.close();
resolve(msg);
}
});
ws.on('error', (err) => {
clearTimeout(timeout);
reject(err);
});
});
}
test('server sends welcome message on connect', async () => {
const msg = await connectAndWaitForMessage(
`ws://localhost:${port}`,
(m) => m.type === 'welcome'
);
expect(msg.type).toBe('welcome');
});This pattern — connectAndWaitForMessage with a predicate — is reusable across all your message-type tests.
Testing Request/Response Flows
For testing that a sent message produces a specific response:
function sendAndReceive(url, outgoing, responsePredicate) {
return new Promise((resolve, reject) => {
const ws = new WebSocket(url);
const timeout = setTimeout(() => {
ws.close();
reject(new Error('No matching response received'));
}, 5000);
ws.on('open', () => {
ws.send(JSON.stringify(outgoing));
});
ws.on('message', (data) => {
const msg = JSON.parse(data.toString());
if (responsePredicate(msg)) {
clearTimeout(timeout);
ws.close();
resolve(msg);
}
});
ws.on('error', reject);
});
}
test('ping receives pong with matching id', async () => {
const response = await sendAndReceive(
`ws://localhost:${port}`,
{ type: 'ping', id: 'test-123' },
(m) => m.type === 'pong'
);
expect(response.type).toBe('pong');
expect(response.id).toBe('test-123');
});
test('subscribe confirms channel', async () => {
const response = await sendAndReceive(
`ws://localhost:${port}`,
{ type: 'subscribe', channel: 'prices' },
(m) => m.type === 'subscribed'
);
expect(response.channel).toBe('prices');
});Collecting Multiple Messages
Real applications often broadcast multiple messages. Here's how to collect a sequence:
function collectMessages(url, count, timeout = 5000) {
return new Promise((resolve, reject) => {
const messages = [];
const ws = new WebSocket(url);
const timer = setTimeout(() => {
ws.close();
reject(new Error(`Only received ${messages.length}/${count} messages`));
}, timeout);
ws.on('message', (data) => {
messages.push(JSON.parse(data.toString()));
if (messages.length >= count) {
clearTimeout(timer);
ws.close();
resolve(messages);
}
});
ws.on('error', reject);
});
}
test('receives welcome then accepts subscriptions', async () => {
const messages = await collectMessages(`ws://localhost:${port}`, 2, (ws) => {
// Send subscribe after connecting — we need a hook here
});
// For ordered flows, use a state machine approach instead
});For ordered multi-step flows, a state machine approach is cleaner:
test('full subscription flow', (done) => {
jest.setTimeout(10000);
const ws = new WebSocket(`ws://localhost:${port}`);
let step = 0;
ws.on('message', (data) => {
const msg = JSON.parse(data.toString());
if (step === 0) {
expect(msg.type).toBe('welcome');
step = 1;
ws.send(JSON.stringify({ type: 'subscribe', channel: 'orders' }));
} else if (step === 1) {
expect(msg.type).toBe('subscribed');
expect(msg.channel).toBe('orders');
ws.close();
done();
}
});
ws.on('error', done);
});Testing Connection Errors and Reconnects
test('client reconnects after server closes connection', async () => {
let connectionCount = 0;
await new Promise((resolve) => {
function connect() {
const ws = new WebSocket(`ws://localhost:${port}`);
ws.on('open', () => {
connectionCount++;
if (connectionCount === 1) {
// Force close from client side
ws.terminate();
} else {
ws.close();
resolve();
}
});
ws.on('close', () => {
if (connectionCount < 2) {
setTimeout(connect, 100); // reconnect after 100ms
}
});
}
connect();
});
expect(connectionCount).toBe(2);
});Mocking WebSockets in Unit Tests
When testing application code that uses WebSockets internally, mock the ws module:
// __mocks__/ws.js
const EventEmitter = require('events');
class MockWebSocket extends EventEmitter {
constructor() {
super();
this.readyState = 1; // OPEN
this.sent = [];
}
send(data) {
this.sent.push(JSON.parse(data));
}
close() {
this.emit('close');
}
}
MockWebSocket.OPEN = 1;
MockWebSocket.CLOSED = 3;
module.exports = { WebSocket: MockWebSocket };Then in tests:
jest.mock('ws');
const { WebSocket } = require('ws');
test('client sends correct subscribe message', () => {
const ws = new WebSocket('ws://example.com');
const client = new MyClient(ws);
client.subscribe('trades');
expect(ws.sent).toContainEqual({ type: 'subscribe', channel: 'trades' });
});Avoiding Jest Hanging
Jest will hang if WebSocket connections remain open after tests. Always close connections in afterEach or inside each test. Use --forceExit as a last resort, but the right fix is proper cleanup:
const openConnections = [];
afterEach(() => {
openConnections.forEach((ws) => {
if (ws.readyState < 2) ws.close(); // OPEN or CONNECTING
});
openConnections.length = 0;
});Complementing with End-to-End Coverage
Unit tests with Jest verify your protocol logic in isolation. But they don't catch issues that only appear in a real browser — WebSocket handshake failures behind proxies, TLS certificate issues, or authentication flows. Tools like HelpMeTest let you add end-to-end WebSocket scenarios using plain English specifications, running in the cloud against your staging environment on every deploy. The combination of Jest for protocol logic and HelpMeTest for full-stack flows gives you fast feedback at both layers without duplicating effort.
Summary
The patterns that matter for WebSocket testing in Jest:
- Wrap message receipt in Promises with timeouts
- Use predicate functions to filter the specific message you expect
- Use state machines for ordered multi-step flows
- Always close connections in cleanup hooks
- Mock
wsfor pure unit tests of client logic - Use
jest.setTimeoutfor any test involving network I/O
WebSocket tests are more verbose than HTTP tests, but the extra structure pays off — protocol bugs in real-time systems are notoriously hard to debug in production.