网站搜索

javascript - 在使用 promise 时 mocha js 断言挂起?


"use strict";
let assert = require("assert");

describe("Promise test", function() {
  it('should pass', function(done) {
    var a = {};
    var b = {};
    a.key = 124;
    b.key = 567;
    let p = new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve();
        }, 100)
    });

    p.then(function success() {

        console.log("success---->", a, b);
        assert.deepEqual(a, b, "response doesnot match");
        done();
    }, function error() {

        console.log("error---->", a, b);
        assert.deepEqual(a, b, "response doesnot match");
        done();
    });
 });
});

输出 :

我正在使用 node v5.6.0。当值不匹配时,测试在断言上似乎会挂起。

我尝试检查是否是使用 setTimeout 的 assert.deepEqual 出现问题,但它工作正常。

但是在使用 Promise 时会失败,如果值不匹配则会挂起。

答案#1

你出现这个错误,是因为你的测试从未完成。这个断言:assert.deepEqual(a, b, "response doesnot match"); 抛出了一个错误,因此由于你没有 catch 块,done 回调从未被调用。

你应该在 promise 链的末尾添加 catch 块:

...
p.then(function success() {
    console.log("success---->", a, b);
    assert.deepEqual(a, b, "response doesnot match");
    done();
}, function error() {
    console.log("error---->", a, b);
    assert.deepEqual(a, b, "response doesnot match");
    done();
})
.catch(done); // <= it will be called if some of the asserts are failed

答案#2

既然你正在使用 Promise,我建议在 it 的末尾直接返回它。一旦 Promise 被解决(成功或失败),Mocha 会认为测试完成并会消费该 Promise。如果 Promise 被拒绝,它会将其值作为抛出的错误使用。

注意:如果你返回一个 Promise,不要声明 done 参数。