If you’re looking for a more expansive tutorial, check out Liam Kaufman’s intro to Socket.io, Mocha, and Node.js. It’s by far the best tutorial I’ve found so far.

I just spent the last three hours trying to create unit tests for my Node.js + Socket.io server with Mocha. I was following all the instructions, but creating a new Socket.io client connection with socket.io-client did nothing. A connection was never established and the node script would finish executing, in spite of my best efforts to attach listeners to the socket. The problem, it turns out, was that I had forgotten to include two critical configuration options when creating the Socket.io client connection. In case anyone is trying to set up unit tests for a socket.io server, here’s a boilerplate test coffeescript file that works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
io = require('socket.io-client')
assert = require("assert")
should = require('should')
 
socketURL = 'http://localhost:9292'
<strong>socketOptions = 
  transports: ['websocket']
  'force new connection': true
</strong>
describe 'Array', () ->
 
  beforeEach (done) ->
    this.socket = io.connect(socketURL, socketOptions)
    this.socket.on 'connect', ()->
      console.log('connected')
      done()
 
  describe '#indexOf()', () ->
    it 'should return -1 when the value is not present', () ->
      assert.equal(-1, [1,2,3].indexOf(5))
      assert.equal(-1, [1,2,3].indexOf(0))

To run this test, place it in a new folder called ‘test’ in your Node.js project. Run the following commands to get the modules you need:

1
2
3
npm install socket.io-client
npm install should
sudo npm install -g mocha

Then, on the command line run:

mocha --compilers coffee:coffee-script