Mocha,应该——当测试包含promise的异步函数时,断言错误是沉默的
Mocha, should - when testing async function that has promise in it, assertion errors are silent
我有一个小问题困扰我…下面的代码显示了一个异步测试,在这个测试中,我们测试了一个我们无法控制的代码(测试的黑盒子,我可以改变它)。
黑盒代码在完成后分派事件,测试监听该事件并断言数据。
问题是当有一个断言错误时,异常被抛出并被promise错误处理程序捕获,而不是由测试框架捕获,因此done函数永远不会执行,并且我们得到超时错误。
很容易通过尝试&catch在it()块中,但是总是使用try &Catch在it()块内?到目前为止,我信任测试框架来处理异常
另一个问题是,错误是沉默的,除非catch输出它,因为它是黑盒子,我们不能指望它。
这里的技巧帮助我解决了这个问题,但我不喜欢解决方案:https://github.com/mochajs/mocha/issues/1128 issuecomment - 40866763它与其他类似的问题不同,因为在it()块中我们没有任何对promise对象的引用。
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();
});
});
在mocha
中测试承诺的方式是返回它们并让它决定何时失败或不失败。
因此,第一步是使承诺在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();
});
相关文章:
- 当已经使用CasperJS选择了css类元素时,断言该类的存在
- Chai深度包含了对嵌套对象的断言
- Mocha/Chai测试链接到函数返回断言错误
- 断言属性不可配置
- 节点回调参数无法断言instanceof Error
- 如何断言后端端点已被调用
- 断言错误:断言失败:坐标数组的长度应与步幅匹配
- Ractive.DEBUG背后的逻辑缩小了断言
- 未捕获的错误:断言失败:余烬视图需要 1.7 和 2.1 之间的 jQuery
- JavaScript 数组克隆相等断言中的远程行为
- 为什么Chrome在“严格模式”下使用块内的功能时仍然保持沉默
- 当“new constructor()”与mocha和chai一起使用时,我如何断言throw
- 断言使用new执行构造函数时抛出错误
- '递归到对象'13076断言在MongoDB中失败
- emberjs追加有效,但引发断言失败错误
- 不可变的Chai断言错误,而预期的结果等于
- 断言var集通过<输入ng模型>不是未定义的
- 断言一个元素是有重点的
- 如何在解析Promise时运行qunit断言
- Mocha,应该——当测试包含promise的异步函数时,断言错误是沉默的