客户端发出信号时如何测试socket.io服务器

时间:2018-12-08 05:08:37

标签: node.js unit-testing sockets socket.io

我希望客户端发出信号,并在接收到该信号时测试我的socket.io服务器的行为。我看过this question和这些博客文章:

jest mocha, chai

但是它们似乎是针对测试客户端而不是服务器。

以下是我要实现的示例:

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

当我运行测试服时,应该会失败,但是不会失败。

有人有测试这种行为的简单例子吗?

当前我正在使用笑话,但是任何框架都可以。

我对socket.io服务器测试的设置和拆卸如下:

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

1 个答案:

答案 0 :(得分:0)

我正在使用摩卡咖啡进行测试。但是我不确定你在做什么。在您的后端套接字服务器中,没有定义的侦听器。

这是测试的一个小例子。也许有帮助吗?!

测试用例

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

服务器:

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

  socket.emit('customerId', null);

});

这是一个非常简单的测试。后端服务器发出连接的客户端“ customerId”,该客户端具有一个customerId的侦听器,并发回其customerId。您还可以采取另一种方法,即在服务器中有一个侦听器,在客户端中有一个发射器。但是我不确定您要做什么。

相关问题