Search code examples
javascriptunit-testingmocha.jsbddchai

Mocha Chai - using 'expect' and want to catch a 'RangeError: Maximum call stack size exceeded' error


I'm using Mocha and Chai as a Javascript testing suite.

I want to catch a 'RangeError: Maximum call stack size exceeded' failure on on of my tests.

JS

function isEven(num){
   if (num === 0) {
      return true;
   } else if (num === 1) {
      return false;
   } else {
      return isEven(num - 2);
  }
}

// Example Call
isEven(-10); //Throws the error 'call stack'

I've been using .throw but with no luck

expect(isEven(-1)).to.throw(ReferenceError, 'RangeError: Maximum call stack size exceeded');

or

expect(isEven(-1)).to.throw(err);

Not having an success with either.

I'm getting the following error in the terminal

npm ERR! Test failed.  See above for more details.

the above details show RangeError: Maximum call stack size exceeded

Any help much appreciated


Solution

  • expect(...).to.throw() requires a function (so Chai can run that function and catch any errors). You're passing it the result of a function (or at least trying to).

    Try this:

    expect(isEven.bind(null, -10)).to.throw(RangeError);
    

    Which is somewhat similar to this:

    function toTest() {
      isEven(-10);
    }
    expect(toTest).to.throw(RangeError);