测试检查房间广播

时间:2016-02-02 16:03:55

标签: unit-testing socket.io mocha

我有一个测试,用于检查用户订阅房间时是否正确发出joined事件。但是,我想编写一个测试,以确保chatUser2加入room2joined事件仅由她收到,而client1 <{1}} <{1}} < / p>

如何编写测试以确保在room1连接时不会调用client1.on('joined')

client2

1 个答案:

答案 0 :(得分:0)

我找到的一个解决方案是here#3

它并没有真正监视任何事情,它只是使用一个变量来计算特定事件被调用的次数。在这种情况下,它应该只被调用一次。

<强> test.js

var should = require('should');
var io = require('socket.io-client');

var socketURL = 'http://0.0.0.0:5000';

var options ={
  transports: ['websocket'],
  'force new connection': true
};

var chatUser1 = {'name':'Tom'};
var chatUser2 = {'name':'Sally'};
var chatUser3 = {'name':'Dana'};

describe("Chat Server",function(){

it('Should be able to send private messages', function(done){
  var client1, client2, client3;
  var message = {to: chatUser1.name, txt:'Private Hello World'};
  var messages = 0;

  var completeTest = function(){
    messages.should.equal(1);
    client1.disconnect();
    client2.disconnect();
    client3.disconnect();
    done();
  };

  var checkPrivateMessage = function(client){
    client.on('private message', function(msg){
      message.txt.should.equal(msg.txt);
      msg.from.should.equal(chatUser3.name);
      messages++;
      if(client === client1){
        /* The first client has received the message
        we give some time to ensure that the others
        will not receive the same message. */
        setTimeout(completeTest, 40);
      };
    });
  };

  client1 = io.connect(socketURL, options);
  checkPrivateMessage(client1);

  client1.on('connect', function(data){
    client1.emit('connection name', chatUser1);
    client2 = io.connect(socketURL, options);
    checkPrivateMessage(client2);

    client2.on('connect', function(data){
      client2.emit('connection name', chatUser2);
      client3 = io.connect(socketURL, options);
      checkPrivateMessage(client3);

      client3.on('connect', function(data){
        client3.emit('connection name', chatUser3);
        client3.emit('private message', message)
      });
    });
  });
});

});

<强> app.js

var io = require('socket.io').listen(5000);
var clients = {};

io.sockets.on('connection', function (socket) {
  var userName;
  socket.on('connection name',function(user){
    userName = user.name;
    clients[user.name] = socket;
    io.sockets.emit('new user', user.name + " has joined.");
  });

  socket.on('message', function(msg){
    io.sockets.emit('message', msg);
  });

  socket.on('private message', function(msg){
    fromMsg = {from:userName, txt:msg.txt}
    clients[msg.to].emit('private message', fromMsg);
  });

  socket.on('disconnect', function(){
    delete clients[userName];
  });
});