Javascript Mocha,should-当测试异步函数时,断言错误是无声的
我有一个小问题困扰着我。。 下面的代码显示了一个异步测试,在该测试中,我们测试了一个我们无法控制的代码(对于测试,我可以更改它) blackbox代码在事件完成时分派事件,测试侦听该事件并断言数据 问题是,当出现断言错误时,promise错误处理程序而不是测试框架会抛出和抛出异常,因此done函数永远不会执行,我们会得到此测试的超时错误 通过在it()块中使用try&catch很容易解决这个问题,但是始终在it()块中使用try&catch是一种好的做法吗?到目前为止,我相信测试框架能够处理异常 另一个问题是,错误是无声的,除非catch打印它,而且由于它的黑盒,我们不能指望它 这里的提示帮助我解决了这个问题,但我不喜欢这些解决方案: 它不同于其他类似的问题,因为在it()块中,我们没有任何对承诺对象的引用Javascript Mocha,should-当测试异步函数时,断言错误是无声的,javascript,asynchronous,promise,mocha.js,chai,Javascript,Asynchronous,Promise,Mocha.js,Chai,我有一个小问题困扰着我。。 下面的代码显示了一个异步测试,在该测试中,我们测试了一个我们无法控制的代码(对于测试,我可以更改它) blackbox代码在事件完成时分派事件,测试侦听该事件并断言数据 问题是,当出现断言错误时,promise错误处理程序而不是测试框架会抛出和抛出异常,因此done函数永远不会执行,我们会得到此测试的超时错误 通过在it()块中使用try&catch很容易解决这个问题,但是始终在it()块中使用try&catch是一种好的做法吗?到目前为止,我相信测试框架能够处理异常
describe.only("test", function () {
var event;
// blackbox simulates a code we have no controler over
// inside this code we have a promise, when this promise resolves it triggers event
var blackbox = function () {
var promise = new Promise(function (resolve, reject) {
resolve();
});
promise.then(function () {
event(4);
}).catch(function (e) {
console.log(e);
});
};
it("async with blackbox promise", function (done) {
// this simulates event listenner, when the event is triggered the code executes
event = function (data) {
// this assertion works and everything is fine
data.should.be.equal(4);
// this assertion thrown exception that is being cought by the promise reject handler and
// isnt cought by the testing framework (chai / mocha)
data.should.be.equal(5);
// because the exception is thrown we never reach the done
done();
};
blackbox();
});
});
你在摩卡咖啡中测试承诺的方式是,你返回承诺,让它来决定何时失败 因此,第一步是在您的
blackbox
函数中提供承诺:
// blackbox simulates a code we have no controler over
// inside this code we have a promise, when this promise resolves it triggers event
var blackbox = function () {
var promise = new Promise(function (resolve, reject) {
resolve();
});
return promise.then(function () {
event(4);
});
// do not catch here unless you want the test to not fail on error
};
现在,让我们更改测试代码以处理承诺:
it("async with blackbox promise", function () {
// this simulates event listenner, when the event is triggered the code executes
event = function (data) {
// this assertion works and everything is fine
data.should.be.equal(4);
// this assertion thrown exception that is being cought by the promise reject handler
data.should.be.equal(5);
};
// mocha will append a rejection handler to this promise here and fail if it gets called
return blackbox();
});
我认为你把一些事情弄混了。始终返回您的承诺,并且在测试承诺时,您不需要
done
回调。只要归还你所有的承诺。还要注意,如果你想摩卡
在被拒绝的承诺
上失败,那么你不必自己抓住
。@MarcoL,这只是一个例子,因为代码是黑盒的-我无法控制它。它可以是第三方库/依赖项,或者您是说黑盒示例代码编写错误?如果代码(来自第三方或黑盒)处理承诺,则它应该向您返回承诺。如果黑盒不返回任何内容,则您无法在此执行异步测试。此外,如果它不给您处理承诺的选择,那么它在内部使用承诺而不是回调这一事实根本不重要。