如何在使用Mocha/Chai调用函数时强制抛出异常

How to force a function to throw exception when it invoked with Mocha/Chai

本文关键字:函数 调用 抛出异常 Chai Mocha      更新时间:2023-09-26

我想测试function B捕获function AMocha/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);
  }
  ...
}

我想强制A抛出异常,而做B的测试。所以我可以确保函数BA正确捕获异常。


搜索了一些帖子后:

Mocha中预期失败的测试

用Mocha/Chai测试JS异常

我没有找到正确答案。


我的问题合理吗?如果是,如何使用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了,你可能会对Sinon感兴趣。它极大地扩展了Mocha功能。在这种情况下,您将使用存根来简化模拟和恢复