开玩笑无法 运行 socket.io 服务器在 React 中测试客户端套接字通信

Unable to run socket.io server in jest for testing client-side socket communication in React

我正在为与 socket.io 的客户端套接字通信编写测试。我正在尝试测试依赖于从服务器接收事件的套接字的连接和其他效果。我试图为我的玩笑测试编写一个服务器,但服务器没有启动。

这是代码示例:

describe('App Communication', () => {
/* Testing flags */
let hasConnected = false;

/* Create server */
const httpServer = createServer();
const sampleMessage = 'Hello world!';
const io = new Server(httpServer);

beforeAll(() => {
    httpServer.listen('4000', () => {
        console.log('listening on 4000');
        io.on('connection', (socket) => {
            hasConnected = true;

            socket.emit('message', sampleMessage);

            socket.on('message', (message) => {
                ...
            });
        });
    });
});
...

有什么方法可以启动服务器并运行?

httpServer.listen是异步的,所以你需要告诉Jest等到服务器启动后运行测试用例:

beforeAll((done) => { // Jest will wait until `done` is called
    httpServer.listen('4000', () => {
        console.log('listening on 4000');
        io.on('connection', (socket) => {
            hasConnected = true;

            socket.emit('message', sampleMessage);

            socket.on('message', (message) => {
                ...
            });
        });
        done();

    });
});

it('should connect to socket', () => {
    // Connect to localhost:4000 here
});