谁能为Node提供一个坚如磐石、极其简单的单元测试呢.js使用WebSocket(Socket.io)?

我用的是插座. node 的io.js,并查看了套接字.io客户端,用于建立与测试中服务器的客户端连接.然而,我似乎错过了一些东西.

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

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 可能会很困难,而非琐碎的例子很快就会变得非常复杂,难以阅读.

NPM提供了一个名为socket.io-await-test的工具,允许您暂停/等待测试,直到使用wait关键字触发事件.

  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相关问答推荐

try 使用Puppeteer抓取Twitter时数组空

Node.js promise 循环中的所有多个API调用

Twilio-获取呼叫录音不起作用的请求

如何在mongodb集合中设置数据限制?

在Docker容器404页面中找不到服务器(提供静态reactjs文件)

向url传递多个参数

一个大型的单个 Redis 实例可以处理所有事情,还是多个 Redis 实例?

Gulp 能否向 Docker 发出增量构建的第一次迭代完成的信号?

加速 sequelize ORM 中的查询

错误:找不到模块'C:\Users\nguye\AppData\Local\nodejs\node_modules\npm\bin\npm-cli.js'

如何在 NestJS 中使用外部生成的 swagger.json?

如何让 vscode 假设一个 node.js 上下文,以便它不假设 `fetch` 存在?

users.watch(在 gmail google api 中)如何收听通知?

如何在 mongoDB 中进行全动态搜索?

等到文件上传完成的有效方法(mongoose )

如何从 Redis 保存和检索会话

通过 POST 请求将数据从 node.js 服务器发送到 node.js 服务器

__dirname 未在 Node 14 版本中定义

将 NodeJS 用于大型项目

为什么 Node.js 被命名为 Node.js?