Lesson 29 / 32

Testing Real-time Code

Write automated tests that start a WebSocket server on a free port, exchange messages and shut down cleanly.

By · 15 years in web development

Making asynchronous tests deterministic

Real-time code is event-driven, so tests fail in confusing ways when they rely on timing. A few habits make them reliable. Use port 0 so the OS picks a free port and parallel tests do not collide. Await events instead of sleeping: Node's events.once() returns a promise for the next open, message or close, so the test waits exactly as long as needed. Separate logic from transport: functions such as message validation, room membership and backoff calculation are plain functions you can unit-test without any socket. Keep a smaller set of integration tests that open a real connection to the real server object. Always clean up: close clients and the server at the end, or the test runner hangs on open handles. For load and soak testing, tools such as k6 and Artillery can open thousands of WebSocket connections and report latency and error rates.

An integration test with node:test

The test starts a server on a random port, connects with Node's built-in client, awaits the reply, and closes everything. Run it with node --test; it reports one passing test.

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { once } from 'node:events';
import { WebSocketServer } from 'ws';

test('echo server replies with a prefix', async () => {
  const wss = new WebSocketServer({ port: 0 }); // 0 = pick a free port
  wss.on('connection', (s) => s.on('message', (m) => s.send(`echo: ${m}`)));
  await once(wss, 'listening');

  const ws = new WebSocket(`ws://localhost:${wss.address().port}`);
  await once(ws, 'open');
  ws.send('ping');
  const [event] = await once(ws, 'message');
  assert.equal(event.data, 'echo: ping');

  ws.close();
  await once(ws, 'close');
  wss.close();
});

Testing a doorbell

You do not test a doorbell by standing outside for exactly ten seconds and hoping someone opens. You press it and wait until the door opens. once(ws, 'message') is waiting for the door, not counting seconds.

Fake timers for heartbeats and backoff

Heartbeat and reconnect logic run on 30-second timers. Use your test runner's mock timers (mock.timers in node:test, vi.useFakeTimers() in Vitest, jest.useFakeTimers() in Jest) to advance time instantly instead of waiting.

Quick check: Why do WebSocket tests often create the server with `port: 0`?

  • Port 0 disables TLS for tests
  • Port 0 makes the server reject real clients
  • The OS assigns a free port, so parallel tests do not clash
  • Port 0 enables automatic reconnection
Answer

The OS assigns a free port, so parallel tests do not clash — Binding to port 0 asks the operating system for any free port; the test reads the real port from `address().port`.