我们都知道,当我在摩卡中回复承诺时,它将测试承诺。
但如果它在promise中抛出异常,如何判断该异常是否抛出。也就是说,如果异常是承诺,则测试通过。
it("Should not take game code for the same user twice", function (done) {
return gameGiftManage.takeGameCode(gameGiftId, userId)
.catch(function (e) {
expect(e).to.exist;
done();
})
})
这是我用来测试异常的测试,但在某些情况下它不会起作用。
takeGameCode:
takeGameCode: function (giftId, userId) {
return GameGiftCode.count({gift: giftId, user: userId}).exec().then(function (c) {
if (c) {
throw '该用户已经领取过礼包';
}
}).then(function () {
return GameGiftCode.findOneAndUpdate({gift: giftId, user: {$exists: false}}, {user: userId}).exec();
}).then(function (a) {
if (!a) {
throw '礼包领完了';
} else {
return a;
}
});
},
答案 0 :(得分:1)
不使用throw,而是在promise中发生错误时使用reject。这就是它的用途。它会触发您尝试断言的.catch()。
另外,为了保持简单,不建议只拒绝()(这实际上就像是说unde undefined)。拒绝(新错误('这里有意义的事情')每次都会产生更一致的结果和更好的测试套件。
这是一篇很棒的文章,可以更深入地了解一些最新情况和为什么http://making.change.org/post/69613524472/promises-and-error-handling
编辑:现在您发布了一些上下文,看起来这是在mongoose的使用范围内,他们的文档有一个很好的例子,说明如何在使用promises时处理错误。而不是使用.catch(),抛出的错误作为第二个参数传递到另一个.then()请参阅this link
所以代替.catch(),你想要
.then(null, function(error){
//handle assertion
})