[英]In Mocha, returning a promise that will be rejected doesn't have the same effect as calling done(err)
The mocha docs state 摩卡文档状态
Alternately, instead of using the done() callback, you may return a Promise.
或者,您可以返回一个Promise,而不是使用done()回调。 This is useful if the APIs you are testing return promises instead of taking callbacks
如果要测试的API返回承诺而不是执行回调,则此方法很有用
But on rejection, these two ways appear to have different results: 但是在拒绝时,这两种方式似乎产生不同的结果:
var Promise = require("bluebird");
describe('failure', function () {
describe('why2describes', function () {
it("fails caught", function (done) {
new Promise(function (resolve, reject) {
reject(new Error("boom"))
}).catch(function (err) {
done(err)
})
});
it("fails return", function (done) {
return new Promise(function (resolve, reject) {
reject(new Error("boom"))
})
});
})
});
The first results in 的第一个结果
Error: boom
The second results in 第二个结果
Unhandled rejection Error: boom
and then additionally states Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
然后另外指出
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
Am I doing something wrong with the 2nd case? 我对第二种情况做错了吗?
Am I doing something wrong with the 2nd case?
我对第二种情况做错了吗?
Yes. 是。 Two things.
两件事情。
When you don't have a catch
handler attached to a Promise chain, the error happens within the chain, will be lost in the form of rejected promise. 当您没有在Promise链上附加
catch
处理程序时,链中发生的错误将以被拒绝的承诺的形式丢失。 Bluebird makes sure that nothing like that happens by detecting and throwing that error 蓝鸟通过检测并抛出该错误来确保不会发生此类情况
Unhandled rejection Error: boom
In async case, calling the done
function is the way let the test processor to know that the current test has completed. 在异步情况下,调用
done
函数是让测试处理器知道当前测试已完成的方式。 In the second case, you never call done
. 在第二种情况下,您永远不会调用
done
。 So it waits for the default timeout, 2000ms, and then fails the test case with that error. 因此,它等待默认超时2000ms,然后由于该错误而使测试用例失败。
But if you like to use the Promises/your API returns a Promise, then you should not use done
function at all. 但是,如果您想使用Promises /您的API返回Promise,则根本不要使用
done
函数。 Your code should look like this 您的代码应如下所示
it("fails return", function () { // no `done` argument here return new Promise(function (resolve, reject) { // ideally you would be doing all the assertions here }) });
The other important thing to note when dealing with Promises based testing is, you should return the promise object. 处理基于Promises的测试时要注意的另一重要事项是,您应该返回promise对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.