简体   繁体   English

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

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

I want to test the function B to catch exception thrown from function A 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);
  }
  ...
}

I want force A to throw exception, while doing the test of B . 我希望在进行B测试时强制A抛出异常。 So I can make sure the function B catch the exception from A correctly. 所以我可以确保函数B正确地从A捕获异常。


After searching some posts: 搜索了一些帖子后:

Test for expected failure in Mocha 测试摩卡的预期失败

Testing JS exceptions with Mocha/Chai 使用Mocha / Chai测试JS异常

I did not find the correct answer. 我找不到正确的答案。


Is my question reasonable? 我的问题合理吗? if it is, how to do that test with Mocha/Chai ? 如果是的话,如何用Mocha/Chai测试?

This is called mocking. 这被称为嘲弄。 For the sake of test of function B you should mock function A to behave the proper way. 为了测试函数B你应该模拟函数A以正确的方式运行。 So before the test you define A something like A = function(){ throw new Error('for test');} call and verify that when called B behaves accordingly. 所以在测试之前你定义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
         });
    }
})

As you're already using Mocha with Chai you might be interested to look into Sinon. 由于你已经和Chai一起使用Mocha,你可能会有兴趣看看Sinon。 It greatly extends Mocha capabilities. 它极大地扩展了Mocha功能。 In this case you would use stubs which simplifies mocking and restoring 在这种情况下,您将使用简化模拟和恢复的存根

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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