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

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

我想测试 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 的测试。所以我可以确保函数 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 来简化模拟和恢复