我想测试函数 B
以使用 Mocha/Chai
捕获从函数 A
抛出的异常。
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
的异常。
搜索一些帖子后:
Test for expected failure in Mocha
Testing JS exceptions with Mocha/Chai
我没有找到正确答案。
我的问题合理吗?如果是,如何使用 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
});
}
})
由于您已经在使用 Mocha 和 Chai,您可能有兴趣研究一下Sinon。它极大地扩展了 Mocha 的功能。在这种情况下,您将使用 stubs这简化了模拟和恢复
关于javascript - 如何强制函数在使用 Mocha/Chai 调用时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31605988/