使用promise时mocha js断言挂起?

act*_*203 5 javascript bdd assert mocha.js node.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();
    });
 });
});
Run Code Online (Sandbox Code Playgroud)

输出: 输出结果

我使用的是节点v5.6.0.当值不匹配时,测试似乎挂起断言.

我尝试使用setTimeout检查assert.deepEqual是否存在问题,但它工作正常.

但是在使用Promise时失败并在值不匹配时挂起.

ale*_*mac 4

您会收到该错误,因为您的测试从未完成。这个断言:assert.deepEqual(a, b, "response doesnot match");抛出一个错误,所以当你没有 catch 块时,done回调函数永远不会被调用。

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
Run Code Online (Sandbox Code Playgroud)