2

I want a client to emit a signal, and test the behaviour of my socket.io server when that signal is received. I have looked at this question and these blog posts:

jest mocha, chai

but they seem to be directed at testing the client, rather than the server.

Here is an example of something that I am trying to implement:

  test('should communicate with waiting for socket.io handshakes', (done) => {

    socket_client.emit('example', 'some messages');

    setTimeout(() => {

      socket_server.on('example', message => {
        expect(message).toBe('INCORRECT MESSAGE');
      });
      done();
    }, 50);

When I run my test suit, this should fail, but doesn't.

Does anyone have a simple example of testing this sort of behaviour?

Currently I'm using jest but any framework is fine.

My set up and teardown of the socket.io server test is as below:

import * as http from 'http';
import ioBack from 'socket.io';

let socket_client;
let httpServer;
let httpServerAddr;
let socket_server;

beforeAll((done) => {
  httpServer = http.createServer().listen();
  httpServerAddr = httpServer.address();
  socket_server = ioBack(httpServer);
  done();
});

afterAll((done) => {
  socket_server.close();
  httpServer.close();
  done();
});
Gerard Simpson
  • 2,026
  • 2
  • 30
  • 45

1 Answers1

0

I am using mocha for testing. But I am not sure what you are doing. In your backend socket server there is no listener that you defined.

Here is a small example for a test. Maybe that helps?!

Test case

var sockethost = websocketUrl;
socketclient = io.connect(sockethost);
socketclient.on('customerId', function(data) {
   var data = {
     customerId: 10,
   }
   socketclient.emit('customerId', data);
});

Server:

var io = require('socket.io')(http);
io.sockets.on('connection', function (socket) {

  socket.emit('customerId', null);

});

So that is a very simple test. The backend server sends out the connected client 'customerId' the client has a listener for customerId and sends back its customerId. You can also do the other way around, that you have a listener in server, and an emit in client. But I am not completely sure what you are trying to do.

bdifferent
  • 703
  • 4
  • 12