gpt4 book ai didi

node.js - 当客户端发出时如何测试 socket.io 服务器

转载 作者:太空宇宙 更新时间:2023-11-04 01:38:42 25 4
gpt4 key购买 nike

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

最佳答案

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

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

测试用例

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。您也可以采取相反的方式,即在服务器中有一个监听器,在客户端有一个发射。但我不完全确定你想做什么。

关于node.js - 当客户端发出时如何测试 socket.io 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53679715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com