SupremeTechnopriest / socket.io-mock

Mock for socket.io
MIT License
38 stars 11 forks source link

[question] how to get io object #1

Closed webeks closed 3 years ago

webeks commented 7 years ago

Is it possible to get io object out of SocketMock?

I need to test

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

And I am not sure how to approach this.

SupremeTechnopriest commented 7 years ago

Hey @webeks,

I think the problem you are running into is that the in operator isn't supported yet. I can add that for you today.

SupremeTechnopriest commented 7 years ago

@webeks

Just to be sure, can you paste the assertions you would like to make?

webeks commented 7 years ago

I am relatively new in socket.io and specially Node so most probably I am trying something really stupid and there is a much better way around it. So just let me know if I make any sense at all :)

Thanks a ton!

Anyway the code I want to test is this:

I have a server.js running in background that is initialized and run before mocha starts:

        sockets = require('./app/sockets'),
        http = require('http');
        var server = http.createServer();
        var io = require('socket.io')({transports:['websocket']});
        io.attach(server);
        var redisIO = require('socket.io-redis');

        io.adapter(redisIO({
            host: 'localhost',
            port: 6379
        }));

        sockets(io);
        server.listen(process.env.port, function (error) {
            if (error) {
              console.error("Unable to listen for connections", error);
              process.exit(10);
            }
        }); 

In sockets I have following

module.exports = function (io) {
  //internal functions get io object so i dont have problems testing public functions
  io.on('connection', function(socket) {
      sendDbChatrooms(socket, io);
  }
}

function sendDbChatrooms(socket, io) {
    ...
   io.of("/").adapter.remoteJoin(socket.id, chatroomId, function (err) {})
}

And then I would like to test private function sendDbChatrooms directly which expects socketand io as params.

it("It should send chatrooms", function (done) {
            var socket = new net.Socket({});
            socket.decoded_token = {};
            socket.decoded_token.uid = 'some uid';

            socket.join = function (arg) {        };

            var sendChatrooms = ApiMock.__get__("sendChatrooms");
            socket.on('chatroom getAll', function (data) {
                done();
            });

             //@todo expect second parameter io => which I dont know how to fake here? :/
            sendChatrooms(socket , io);
        });
SupremeTechnopriest commented 4 years ago

Right I see. We would have to mock out the io object. I personally don't use socket.io anymore, but if you want to take this on and submit a PR I can get it merged in.