8

我正在使用标准配置的 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
 }

switch 中调用的每个方法都会向客户端发送回一条消息。

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);
        } 
    })
};

现在我的问题是我想对我的代码进行测试(迟到总比没有好)而且我不知道该怎么做。我开始用 mocha + supertest 编写普通的 http 测试,但我只是不知道如何处理 websockets。

我希望只有一个 websocket 连接可以在所有测试中重用,我在第一条消息后将 websocket 连接与用户会话绑定,我也想测试这种持久性。

如何利用 ws 客户端的 onmessage 事件并在我的测试中使用它?测试如何区分收到的消息并知道他们应该等待哪个消息?

4

1 回答 1

2

工作中的同事问它是否真的需要一个客户端连接,或者是否有可能只是模拟它。事实证明这是要走的路。我写了一个小助手类 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);
        }
    }
}

现在在我的摩卡测试中我只是做

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();
        })
    })
})

它就像一个魅力和持久连接状态和请求之间的变量。

于 2014-01-24T16:24:41.600 回答