After further pushing and pushing, I found incredibly useful information at http://blog.foundry376.com/2012/09/connecting-to-a-socket-io-server-from-node-js-unit-tests . In the author’s example, he points to a critical step in setting up socket listeners in “before *” hooks. This example works (assuming the server is listening on socket connections on localhost: 3001, of course)
var io = require('socket.io-client') , assert = require('assert') , expect = require('expect.js'); describe('Suite of unit tests', function() { var socket; beforeEach(function(done) { // Setup socket = io.connect('http://localhost:3001', { 'reconnection delay' : 0 , 'reopen delay' : 0 , 'force new connection' : true }); socket.on('connect', function() { console.log('worked...'); done(); }); socket.on('disconnect', function() { console.log('disconnected...'); }) }); afterEach(function(done) { // Cleanup if(socket.connected) { console.log('disconnecting...'); socket.disconnect(); } else { // There will not be a connection unless you have done() in beforeEach, socket.on('connect'...) console.log('no connection to break...'); } done(); }); describe('First (hopefully useful) test', function() { it('Doing some things with indexOf()', function(done) { expect([1, 2, 3].indexOf(5)).to.be.equal(-1); expect([1, 2, 3].indexOf(0)).to.be.equal(-1); done(); }); it('Doing something else with indexOf()', function(done) { expect([1, 2, 3].indexOf(5)).to.be.equal(-1); expect([1, 2, 3].indexOf(0)).to.be.equal(-1); done(); }); }); });
I found that placing done () in a beforeEach listener, socket.on ('connect' ...) is crucial to establish a connection. For example, if you comment out done () in a listener, add it to one area (just before exiting beforeEach), you will see the message "no connection to break ..." instead of "disconnecting ..". For example:
beforeEach(function(done) { // Setup socket = io.connect('http://localhost:3001', { 'reconnection delay' : 0 , 'reopen delay' : 0 , 'force new connection' : true }); socket.on('connect', function() { console.log('worked...'); //done(); }); socket.on('disconnect', function() { console.log('disconnected...'); }); done(); });
I am new to Mocha, so there may be a very obvious reason to initialize for put done () with the socket scope itself. I hope this little detail saves others on my boots from pulling hair.
For me, the above test (with the correct done () score) outputs:
Suite of unit tests First (hopefully useful) test ◦ Doing some things with indexOf(): worked... ✓ Doing some things with indexOf() disconnecting... disconnected... ◦ Doing something else with indexOf(): worked... ✓ Doing something else with indexOf() disconnecting... disconnected... 2 tests complete (93 ms)