[英]How to force a function to throw exception when it invoked with Mocha/Chai
我想测试function B
以捕获从function A
抛出的异常与Mocha/Chai
。
function A() {
// 1. the third party API is called here
// some exception may be thrown from it
...
// 2. some exception could be thrown here
// caused by the logic in this function
}
function B() {
// To catch exception thrown by A()
try {
A();
} catch(err) {
console.error(err);
}
...
}
我希望在进行B
测试时强制A
抛出异常。 所以我可以确保函数B
正确地从A
捕获异常。
搜索了一些帖子后:
我找不到正确的答案。
我的问题合理吗? 如果是的话,如何用Mocha/Chai
测试?
这被称为嘲弄。 为了测试函数B
你应该模拟函数A
以正确的方式运行。 所以在测试之前你定义A
像A = function(){ throw new Error('for test');}
调用并验证当被调用时B
行为相应。
describe('alphabet', function(){
describe('A', function(){
var _A;
beforeEach(function(){
var _A = A; //save original function
A = function () {
throw new Error('for test');
}
});
it('should catch exceptions in third party', function(){
B();
expect(whatever).to.be.true;
});
afterEach(function(){
A = _A;//restore original function for other tests
});
}
})
由于你已经和Chai一起使用Mocha,你可能会有兴趣看看Sinon。 它极大地扩展了Mocha功能。 在这种情况下,您将使用简化模拟和恢复的存根
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.