摩卡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(); }); }); }); 

输出: 输出结果

我正在使用节点v5.6.0。 当值不匹配时,testing似乎挂起来断言。

我试图用setTimeout来检查assert.deepEqual是否存在问题,但是工作正常。

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

你得到这个错误,因为你的testing从未完成。 这个断言: assert.deepEqual(a, b, "response doesnot match"); 抛出一个错误,所以你没有捕获块, donecallback从来没有被调用。

您应该在承诺链的末尾添加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 

既然你正在使用Promise,我build议在它结束的时候把it 。 一旦该承诺解决(履行或拒绝),摩卡将考虑testing完成,它会消耗承诺。 在被拒绝的Promise的情况下,它将使用它的值作为抛出的Error。

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