Skip to main content
Latest blog post (July 25, 2024): npm package provenance.
Version: 4.x

Testing

You will find below some code examples with common testing libraries:

  • mocha
  • jest
  • tape
  • vitest
  • CommonJS
  • ES modules
  • TypeScript

Installation:

npm install --save-dev mocha chai

Test suite:

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

functionwaitFor(socket, event){
returnnewPromise((resolve)=>{
socket.once(event, resolve);
});
}

describe("my awesome project",()=>{
let io, serverSocket, clientSocket;

before((done)=>{
const httpServer =createServer();
io =newServer(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("should work",(done)=>{
clientSocket.on("hello",(arg)=>{
assert.equal(arg,"world");
done();
});
serverSocket.emit("hello","world");
});

it("should work with an acknowledgement",(done)=>{
serverSocket.on("hi",(cb)=>{
cb("hola");
});
clientSocket.emit("hi",(arg)=>{
assert.equal(arg,"hola");
done();
});
});

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

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

returnwaitFor(serverSocket,"baz");
});
});

Reference: https://mochajs.org/

AltStyle によって変換されたページ (->オリジナル) /