node.js - 测试 Mocha 中的预期超时

标签 node.js mocha.js

我有一个 Faye 发布/订阅服务器,仅当消息已发送给其他订阅者时,它才会向新订阅者发送消息。我正在使用 mocha 进行单元测试。

此测试旨在确认基本功能:

    it('should send a special message to new subscribers', function(done){
        testerPubSub.setLastJsonContent('some arbitrary content');
        var subscription = client.subscribe("/info", function(message) {
            assert.equal(true, message.text.indexOf('some arbitrary content') !== -1, 'new subscriber message not sent');
            done();
        });
        subscription.cancel();
    });

但我现在想测试没有向以前的订阅者发送消息的情况。这个测试类似于:

    it('should not send a special message to new subscribers if no data has been retrieved', function(done){
        testerPubSub.setLastJsonContent(null);
        var messageReceived = false;
        var subscription = client.subscribe("/sales", function(message) {
            messageReceived = true;
        });

        ////need to magically wait 2 seconds here for the subscription callback to timeout

        assert.equal(false, messageRecieved, 'new subscriber message received');
        subscription.cancel;
        done();
    });

当然,神奇的 sleep 功能是有问题的。有没有更好的方法来进行这种“我希望回调永远不会被触发”测试?

谢谢, 迈克

最佳答案

我想到了一个可能的解决方案,但它有点太依赖于我将其视为解决方案的时间:

    it('should not send a special message to new subscribers if no data has been retrieved', function(done){
        testerPubSub.setLastJsonContent(null);
        var messageReceived = false;
        var subscription = client.subscribe("/sales", function(message) {
            assert.fail(message.text, '', 'Should not get message', '=');
        });
        setTimeout(function(){
            done();
        }, 1500);

        subscription.cancel;
    });

这个测试通过了,但是 1500 毫秒的暂停似乎相当随意。我真的是在说“在我认为它会超时之前,跳出来说没问题。

关于node.js - 测试 Mocha 中的预期超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17647069/

相关文章:

node.js - 503 "Service Unavailable"安装 iisnode 后所有应用程序均出现错误

node.js - 在mongodb中创建空集合

javascript - 包含一个文件夹和其中的文件以使用 Electron 构建器进行 Electron 构建?

javascript - 为什么在挂载过程中组件中未定义这个全局本地 Vue 属性?

javascript - Mocha 使用之前测试的数据

node.js - 在 ElectronJS (Windows) 中以高质量和最小尺寸记录屏幕

node.js - "required:true"的 Mongoose 验证器无法正常工作

javascript - 未处理的 promise 拒绝警告。使用 npm run test 运行时的警告

reactjs - 导入react-bootstrap组件测试失败

typescript - 纽约市( Istanbul 尔)从覆盖率报告中排除测试代码