繁体   English   中英

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

[英]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测试JS异常

我找不到正确的答案。


我的问题合理吗? 如果是的话,如何用Mocha/Chai测试?

这被称为嘲弄。 为了测试函数B你应该模拟函数A以正确的方式运行。 所以在测试之前你定义AA = 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM