Mocha异步测试超时的解决方案

Workaround for Mocha async test timeouts

本文关键字:解决方案 超时 测试 异步 Mocha      更新时间:2023-09-26

我正在尝试用摩卡和chai编写单元测试,但是我遇到了一个问题,我得到超时错误,而不是实际错误被抛出,我似乎找不到解决办法。

Error I'm get:

  1) Unit Tests for Networks Array
 should check that networks array is not empty:
     Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.

在我的代码中,我让测试结果的反面为真,所以我有一个预期的失败。

有一个标准的方法来解决这种事情吗?

describe('Unit Tests for Networks Array'n', function () {
    it('should check that networks array is not empty', function (done) {
        git.getNetworks(function (networks) {
            expect(networks).to.be.empty();  // expected failure
            done();
        });
    });

Promises就是这样工作的,你可以拒绝它或者解决它。但是,如果在你的承诺逻辑中有一个错误,你没有捕捉到这个错误,因为它被吞下了,然后无声地死亡,永远不会出现。

git.getNetworks.then(function() { 
/* do something with the result */
}).catch(function() {
 /* error :( */
})

确保覆盖了拒绝回调(可选)和捕获(总是),否则Promise会无声地抛出和错误,这就是为什么Mocha发送超时