Unit testing Node.js and WebSockets (Socket.io)
node.js, socket.io, unit-testing, websocket
Solution
Dealing with callbacks and promises yourself can be difficult and non trivial examples quickly become very complex and hard to read.
There is a tool called socket.io-await-test available via NPM that allows you to suspend/wait in a test until events have been triggered using the await keyword.
describe("wait for tests", () => {
it("resolves when a number of events are received", async () => {
const tester = new SocketTester(client);
const pongs = tester.on('pong');
client.emit('ping', 1);
client.emit('ping', 2);
await pongs.waitForEvents(2) // Blocks until the server emits "pong" twice.
assert.equal(pongs.get(0), 2)
assert.equal(pongs.get(1), 3)
})
})
Problem
Could anyone provide a rock-solid, dead-simple unit test for Node.js using WebSockets (Socket.io)? I'm using socket.io for Node.js, and have looked at socket.io-client for establishing the client connection to a server in the test. However, I seem to be missing something. In the example below, "worked..." never gets printed out. ``` var io = require('socket.io-client') , assert = require('assert') , expect = require('expect.js'); describe('Suite of unit tests', function() { describe('First (hopefully useful) test', function() { var socket = io.connect('http://localhost:3001'); socket.on('connect', function(done) { console.log('worked...'); done(); }); it('Doing some things with indexOf()', function() { expect([1, 2, 3].indexOf(5)).to.be.equal(-1); expect([1, 2, 3].indexOf(0)).to.be.equal(-1); }); }); }); ``` Instead, I simply get: ``` Suite of unit tests First (hopefully useful) test ✓ Doing some things with indexOf() 1 test complete (26 ms) ``` Any suggestions?