简体   繁体   中英

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 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 . So I can make sure the function B catch the exception from A correctly.


After searching some posts:

Test for expected failure in Mocha

Testing JS exceptions with Mocha/Chai

I did not find the correct answer.


Is my question reasonable? if it is, how to do that test with Mocha/Chai ?

This is called mocking. For the sake of test of function B you should mock function A to behave the proper way. 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.

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. It greatly extends Mocha capabilities. In this case you would use stubs which simplifies mocking and restoring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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