单元测试 Node.js 和 WebSockets (Socket.io) [英] Unit testing Node.js and WebSockets (Socket.io)

查看:28
本文介绍了单元测试 Node.js 和 WebSockets (Socket.io)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以使用 WebSockets (Socket.io) 为 Node.js 提供坚如磐石、极其简单的单元测试吗?

Could anyone provide a rock-solid, dead-simple unit test for Node.js using WebSockets (Socket.io)?

我正在将 socket.io 用于 Node.js,并查看了 socket.io-client 以在测试中建立与服务器的客户端连接.然而,我似乎错过了一些东西.

I'm using socket.io for Node.js, and have looked at socket.io-client for establishing the client connection to a server in the test. However, I seem to be missing something.

在下面的例子中,worked..."永远不会被打印出来.

In the example below, "worked..." never gets printed out.

var io = require('socket.io-client')
, assert = require('assert')
, expect = require('expect.js');

describe('Suite of unit tests', function() {

    describe('First (hopefully useful) test', function() {

        var socket = io.connect('http://localhost:3001');
        socket.on('connect', function(done) {
            console.log('worked...');
            done();
        });

        it('Doing some things with indexOf()', function() {
            expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
            expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
        });

    });
});

相反,我只是得到:

  Suite of unit tests
    First (hopefully useful) test
      ✓ Doing some things with indexOf() 


  1 test complete (26 ms)

有什么建议吗?

推荐答案

自己处理回调和 Promise 可能很困难,非平凡的例子很快就会变得非常复杂和难以阅读.

Dealing with callbacks and promises yourself can be difficult and non trivial examples quickly become very complex and hard to read.

有一个工具叫做socket.io-await-test可通过 NPM 获得,它允许您在测试中暂停/等待,直到使用 await 关键字触发事件.

There is a tool called socket.io-await-test available via NPM that allows you to suspend/wait in a test until events have been triggered using the await keyword.

  describe("wait for tests", () => {
    it("resolves when a number of events are received", async () => {
        const tester = new SocketTester(client);
        const pongs = tester.on('pong');
        
        client.emit('ping', 1);
        client.emit('ping', 2);
        await pongs.waitForEvents(2) // Blocks until the server emits "pong" twice. 

        assert.equal(pongs.get(0), 2)
        assert.equal(pongs.get(1), 3)
    })
})

这篇关于单元测试 Node.js 和 WebSockets (Socket.io)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆