如何testingnode.js websocket服务器?

我正在使用标准configuration的sockjs。

var ws = sockjs.createServer(); ws.on('connection', function(conn) { conn.on('data', function(message) { wsParser.parse(conn, message) }); conn.on('close', function() { }); }); var server = http.createServer(app); ws.installHandlers(server, {prefix:'/ws'}); server.listen(config.server.port, config.server.host); 

wsParser.parse函数是这样工作的:

 function(conn, message) { (...) switch(message.action) { case "titleAutocomplete": titleAutocomplete(conn, message.data); break; (...) // a lot more of these } 

交换机中调用的每个方法都会向客户端发回消息。

 var titleAutocomplete = function(conn, data) { redis.hgetall("titles:"+data.query, function(err, titles){ if(err) ERR(err); if(titles) { var response = JSON.stringify({"action": "titleAutocomplete", "data": {"titles": titles}}); conn.write(response); } }) }; 

现在我的问题是,我想为我的代码进行testing(比从未猜到更晚),我不知道该怎么做。 我开始使用mocha + supertest编写正常的httptesting,但是我只是不知道如何处理websocket。

我想通过所有的testing只有一个websocket连接重用,我绑定websocket连接用户会话后第一条消息,我也想testing持久性。

我如何利用ws客户端的onmessage事件并在我的testing中使用它? testing如何分辨收到的信息,并知道他们应该等待哪一个?

在工作的同事问,如果它真的需要客户端连接,或者只是嘲笑它。 事实certificate,这是要走的路。 我写了一个小帮手类wsMockjs

 var wsParser = require("../wsParser.js"); exports.createConnectionMock = function(id) { return { id: id, cb: null, write: function(message) { this.cb(message); }, send: function(action, data, cb) { this.cb = cb; var obj = { action: action, data: data } var message = JSON.stringify(obj); wsParser.parse(this, message); }, sendRaw: function(message, cb) { this.cb = cb; wsParser.parse(this, message); } } } 

现在在我的摩卡testing中,我只是做了

 var wsMock = require("./wsMock.js"); ws = wsMock.createConnectionMock("12345-67890-abcde-fghi-jklmn-opqrs-tuvwxyz"); (...) describe('Websocket server', function () { it('should set sessionId variable after handshake', function (done) { ws.send('handshake', {token: data.token}, function (res) { var msg = JSON.parse(res); msg.action.should.equal('handshake'); msg.data.should.be.empty; ws.should.have.property('sessionId'); ws.should.not.have.property('session'); done(); }) }) it('should not return error when making request after handshake', function (done) { ws.send('titleAutocomplete', {query: "ter"}, function (res) { var msg = JSON.parse(res); msg.action.should.equal('titleAutocomplete'); msg.data.should.be.an.Object; ws.should.have.property('session'); done(); }) }) }) 

它像一个魅力和坚持连接状态和请求之间的variables。