Skip to main content
Version: 4.x

Testing

Testing a Socket.IO application usually involves writing integration tests, where you start a real Socket.IO server, connect a client to it, and assert that events are properly exchanged between the two sides.

The examples below show how to test a basic Socket.IO setup with common testing libraries. Each example covers:

  • sending an event from the server to the client
  • sending an event from the client to the server with an acknowledgement
  • using emitWithAck()
  • waiting for an event with a small helper function

Select your preferred test runner:

Installation:

Built-in since Node.js v18, no installation is required.

Test suite:

test/basic.test.js
const { test } = require("node:test");
const assert = require("node:assert");
const { createServer } = require("node:http");
const { Server } = require("socket.io");
const ioc = require("socket.io-client");

function waitFor(socket, event) {
return new Promise((resolve) => {
socket.once(event, resolve);
});
}

test("my awesome project", async (t) => {
let io, serverSocket, clientSocket;

await t.test("setup", () => {
return new Promise((resolve) => {
const httpServer = createServer();
io = new Server(httpServer);
io.on("connection", (socket) => {
serverSocket = socket;
});
httpServer.listen(() => {
const port = httpServer.address().port;
clientSocket = ioc(`http://localhost:${port}`);
clientSocket.on("connect", resolve);
});
});
});

t.after(() => {
io.close();
clientSocket.disconnect();
});

await t.test("should work", () => {
return new Promise((resolve) => {
clientSocket.on("hello", (arg) => {
assert.strictEqual(arg, "world");
resolve();
});
serverSocket.emit("hello", "world");
});
});

await t.test("should work with an acknowledgement", () => {
return new Promise((resolve) => {
serverSocket.on("hi", (cb) => {
cb("hola");
});
clientSocket.emit("hi", (arg) => {
assert.strictEqual(arg, "hola");
resolve();
});
});
});

await t.test("should work with emitWithAck()", async () => {
serverSocket.on("foo", (cb) => {
cb("bar");
});
const result = await clientSocket.emitWithAck("foo");
assert.strictEqual(result, "bar");
});

await t.test("should work with waitFor()", () => {
clientSocket.emit("baz");

return waitFor(serverSocket, "baz");
});
});

Reference: https://nodejs.org/api/test.html