Skip to content

Instantly share code, notes, and snippets.

@cmac1000
Created June 9, 2014 16:48
Show Gist options
  • Save cmac1000/d2029989ef87dbc4da3c to your computer and use it in GitHub Desktop.
Save cmac1000/d2029989ef87dbc4da3c to your computer and use it in GitHub Desktop.
var ioClient = require('socket.io-client')
var should = require('should');
var chai = require('chai');
var options ={
transports: ['websocket'],
'force new connection': true,
'reconnection delay' : 0,
'reopen delay' : 0
};
var socketUrl = 'http://localhost:3000';
describe('chat server', function() {
// The maintaining-state issue is fixed by using beforeEach()
// to create a new ioServer.
beforeEach(function(done) {
console.log('before called');
var ioServer = require('../index.js');
done();
});
// Overkill, I think, to set ioServer back to null after each test.
// afterEach(function(done) {
// console.log('after called')
// var ioServer = null;
// done();
// })
// 'user join' event should receive 'login' event
it('should emit "user joined" and receive "login"', function(done) {
// I thought it might be useful to define all the clients at the bottom
// of the describe function, but this seems to work fine, as well
// as being easier to read and isolating variable to their test cases.
var client1 = ioClient(socketUrl, options);
client1.on('connect', function () {
console.log('test client 1 connected');
client1.on('user joined', function (data) {
console.log('test client got a user joined event');
});
client1.on('login', function (data) {
console.log('test client got a login event');
chai.assert.equal(data.numUsers, 1)
client1.disconnect();
done();
})
client1.emit('add user', 'Foobert');
});
});
// 2 clients log in, one client sends a message, the other client gets it.
it('should dispatch chat messages from client2 to client3', function (done) {
var client2 = ioClient(socketUrl, options);
var client3 = ioClient(socketUrl, options);
client2.on('connect', function () {
console.log('test client 2 connected');
client3.on('connect', function () {
console.log('test client 3 connected');
client2.emit('new message', 'Hello Donovan!');
client3.on('new message', function (data) {
chai.assert.equal(data.message, 'Hello Donovan!');
client2.disconnect();
client3.disconnect();
done();
});
})
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment