【问题标题】:How to test socket.io server when client emits客户端发出时如何测试socket.io服务器
【发布时间】:2019-05-09 19:42:34
【问题描述】:

我希望客户端发出信号,并在收到该信号时测试我的 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);

当我运行我的测试套装时,这应该会失败,但不会。

有没有人有一个简单的例子来测试这种行为?

目前我正在使用 jest,但任何框架都可以。

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

【问题讨论】:

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


    【解决方案1】:

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

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

    测试用例

    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。你也可以反过来做,你在服务器上有一个监听器,在客户端有一个发射器。但我不完全确定您要做什么。

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2018-06-28
      相关资源
      最近更新 更多