Ir al contenido principal
Versión: 4.x

Pruebas

A continuación encontrarás algunos ejemplos de código con bibliotecas de pruebas comunes:

Instalación:

npm install --save-dev mocha chai

Suite de pruebas:

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

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

describe("mi proyecto increíble", () => {
let io, serverSocket, clientSocket;

before((done) => {
const httpServer = createServer();
io = new Server(httpServer);
httpServer.listen(() => {
const port = httpServer.address().port;
clientSocket = ioc(`http://localhost:${port}`);
io.on("connection", (socket) => {
serverSocket = socket;
});
clientSocket.on("connect", done);
});
});

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

it("debería funcionar", (done) => {
clientSocket.on("hello", (arg) => {
assert.equal(arg, "world");
done();
});
serverSocket.emit("hello", "world");
});

it("debería funcionar con una confirmación", (done) => {
serverSocket.on("hi", (cb) => {
cb("hola");
});
clientSocket.emit("hi", (arg) => {
assert.equal(arg, "hola");
done();
});
});

it("debería funcionar con emitWithAck()", async () => {
serverSocket.on("foo", (cb) => {
cb("bar");
});
const result = await clientSocket.emitWithAck("foo");
assert.equal(result, "bar");
});

it("debería funcionar con waitFor()", () => {
clientSocket.emit("baz");

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

Referencia: https://mochajs.org/