我正在尝试将TDD原则应用于使用node.js和nodeunit进行单元测试的应用程序。我正在努力创建一个能够使用websockets来测试应用程序通信协议的测试用例。
我对TDD很新,所以,这种方法对于TDD是否正确?
您知道我在哪里可以找到样品吗?
编辑: 我有一份工作样本。但是我遇到的问题是服务器关闭它需要15秒。我很感激有关此代码的反馈(这是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;
答案 0 :(得分:1)
在阅读How does one properly shutdown socket.io / websocket-client?后,我发现添加'close timeout'和'client store expiration'帮助我在jasmin测试中使用socket.io-client解决了类似的问题。在服务器上,添加这些行(在咖啡中):
app = module.exports = express.createServer()
io = require('socket.io').listen(app)
io.set 'close timeout', 0.2
io.set 'client store expiration', 0.2
然后在客户端中添加这些参数('reconnect'和'强制新连接'):
socket = io.connect('http://localhost:5555', {'reconnect': false, 'force new connection': true})