使用Mocha内置的Promise支持测试失败的Promise [英] testing failed promises with mocha's built-in promise support
问题描述
我应该如何与mocha和chai一起测试我的诺言失败了?
How should I be testing, with mocha and chai, that my promise has failed?
我很困惑,因为我最初以为我应该使用'mocha-as-promised',但是那 现在已弃用该软件包(我使用的是Mocha 2.1.0),并建议 只需使用摩卡咖啡内置的承诺测试即可. 参见: https://github.com/domenic/mocha-as-promised
I am confused, because I initially thought I should be using 'mocha-as-promised', but that package is now deprecated (I'm using mocha 2.1.0), with the advice to just use the promise testing that's now built into mocha. see: https://github.com/domenic/mocha-as-promised
另一篇文章建议取消对 it()回调-不知道我为什么会这样,因为我知道 传递"done"参数是表明测试已通过的方式 正在异步测试. 请参阅:如何正确地使用摩卡和柴对诺言进行测试?
Another post recommends doing away with the 'done' argument to the it() callback - not sure I understand why, since my understanding that passing in the 'done' parameter was the way to signal that a test was being tested asynchronously. see: How do I properly test promises with mocha and chai?
无论如何,我试图将问题简化为以下代码-请帮助我进行修改,以便我可以测试我的诺言确实失败了.
Anyway, I've tried to reduce my issue to the below code - please help me modify this so that I can test that my promise indeed fails.
it.only("do something (negative test)", function (done) {
var Q = require('q');
function makePromise() {
var deferred = Q.defer();
deferred.reject(Error('fail'));
return deferred.promise;
};
makePromise()
.then(done, done);
});
推荐答案
进行更多的挖掘,看来正确的方法是添加一个额外的catch块,就像这样...
Some more digging, and it appears the right way is to add an additional catch block, like so...
it.only("do something (negative test)", function (done) {
var Q = require('q');
function makePromise() {
var deferred = Q.defer();
deferred.reject(Error('fail'));
return deferred.promise;
};
makePromise()
.catch(function(e) {
expect(e.message).to.equal('fail');
})
.then(done, done);
});
我对其他想法感兴趣,或者确认这是一种很好的方式..谢谢.
I'm interested in alternative ideas, or confirmation that this is fine the way it is.. thanks.
更新:
Ben-现在,我想知道你在说什么,尤其是.在本杰明·G的简短但有益的评论之后.
总结:
当您传递一个done
参数时,预期该测试将通过调用done()
函数来触发其完成";
When you pass in a done
parameter, the test is expected to trigger it's 'done-ness' by calling the done()
function;
当您不传递done
参数时,它通常仅适用于同步调用.然而,
如果您 返回 一个承诺,那么mocha框架(mocha> 1.18)将捕获通常会被吞噬的所有失败(根据promise规范).这是更新的版本:
When you don't pass in a done
parameter, it normally only works for synchronous calls. However,
if you return a promise, the mocha framework (mocha >1.18) will catch any failures that normally would have been swallowed (per the promises spec). Here is an updated version:
it.only("standalone neg test for mocha+promises", function () {
var Q = require('q');
function makePromise() {
var deferred = Q.defer();
deferred.reject(Error('fail'));
return deferred.promise;
};
return makePromise()
.catch(function(e) {
expect(e.message).to.equal('fail');
});
});
这篇关于使用Mocha内置的Promise支持测试失败的Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!