I am trying to apply the TDD principles to an application using node.js and nodeunit for the unit test. I am struggling trying to create a test case that is able to use websockets to test the application communication protocol.
I am quite new to TDD, so, is this approach correct for the TDD ?
Do you know where can I find samples to to this ?
EDIT: I have a working sample. However I have the problem that the server takes 15 seconds in closing it self. I appreciate feedback about this code (this is WIP).
file tests/websocket.js
var Server = require('../tests/server.js').Server;
var wsServer = new Server();
var ioclient = require("socket.io-client");
var testCase = require('nodeunit').testCase;
exports.server = testCase({
setUp: function(callback) {
wsServer.initialize();
wsServer.addEvent('connection',function(socket){
socket.on('ping',function(data){
socket.emit('ping', { value: 'ok' });
socket.disconnect();
});
});
callback();
},
tearDown: function (callback) {
wsServer.close();
callback();
},
'ping test': function(test) {
var clientsocket = ioclient.connect( 'http://localhost:' + wsServer.getPort() );
clientsocket.on('ping', function(data){
test.equal('ok', data.value);
test.done();
});
clientsocket.emit('ping', { pingRequest: '1' });
},
'another ping test': function(test) {
var clientsocket = ioclient.connect( 'http://localhost:' + wsServer.getPort() );
clientsocket.on('ping', function(data){
test.equal('ok', data.value);
test.done();
});
clientsocket.emit('ping', { pingRequest: '1' });
}
});
file test/server.js
function Server() {
this.port = 3333;
}
Server.prototype.initialize = function () {
this.create();
}
Server.prototype.getPort= function () {
return this.port;
}
Server.prototype.addEvent = function (name, fn) {
this.instance.sockets.on(name, fn);
}
Server.prototype.create = function () {
var io = require("socket.io").listen(this.port, {'log level': 1});
//io.sockets.on('connection',);
this.instance = io;
}
Server.prototype.close = function () {
this.port ++;
this.instance.server.close();
}
exports.Server = Server;