【问题标题】:Nodejs Assert not executing into Mocha testsNodejs Assert 未执行到 Mocha 测试中
【发布时间】:2013-12-21 22:39:59
【问题描述】:

我遇到了一个奇怪的问题,我为我的模块编写了多个测试,但最后一个没有工作。我测试了一个异步函数,一切都很好,除非测试失败。我不知道为什么,但是 assert.equal 之后的代码没有被执行。如果测试成功,则正确调用 done。

describe('download', function(){

    it('should download pictures from given URLs', function(done){
        Download.download(list, function(){

            var pictures = fs.readdirSync("exports/merge/");

            console.log('before assert - '+pictures.length);
            assert.equal(pictures.length, 3);
            console.log('before done - '+pictures.length);
            done();
        });
    });
});

打印了“断言之前”的日志,然后什么也没有发生。 如果 I pictures.length 等于 3,则正确调用了 done()。

【问题讨论】:

  • 第一个console.logpictures.length 输出什么?可能是undefined 或其他什么..
  • 不,它是一个 int,如果是 3,一切正常,当它是一个非 3 的 int 时会出现错误。
  • 输出什么信息?
  • 似乎没有显示此测试中发生的任何错误,并且执行等待超时。我不知道,范围错误或其他任何东西。
  • 好的,问题来自我的下载功能的承诺。 mocha 无法检索错误,因为它们被抛出到 Promise 中。当我找到检索错误的方法时将发布一个回答

标签: node.js unit-testing assert mocha.js


【解决方案1】:

Promise 吞下错误。为了让它们被抛出,最简单的解决方案是用 .done() 结束 Promise 链。

    var p = Download.download(list, function(){

        var pictures = fs.readdirSync("exports/merge/");

        console.log('before assert - '+pictures.length);
        assert.equal(pictures.length, 3);
        console.log('before done - '+pictures.length);
        done();
    });
    p.done();

有关该主题的更多信息,请参阅 bluebird's documentationQ's documentation

当你到达一个 Promise 链的末尾时,你应该返回最后一个 Promise 或结束链。由于处理程序会捕获错误,因此无法观察到异常是一种不幸的模式。 所以,要么返回它或结束它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多