Why does Jasmine fail on my raising and catching an error?

Viewed 24

I am raising the same error I am trying to catch but not catching it

My code is:

SimpleMath.prototype.getFactorial = function(number) {
  if (number < 0) {
    throw new Error("Cannot be less than zero");
  }
  else if (number == 0) {
    return 0;
  }
  else if (number == 1) {
    return 1;
  }
  else {
    return number * this.getFactorial(number-1);
  }
}

My tests are as follows. The first 2 works but the last one that raises the exception fails:

describe("SimpleMath", function() {
  var simpleMath;

  beforeEach(function() {
    simpleMath = new SimpleMath();
    var result;
  }); 

  it("should calculate a factorial for a positive number", function() {
    result=simpleMath.getFactorial(3);
    expect(result).toEqual(6);
  }); 

  it("should calculate a factorial for 0 - which will be zero", function() {
    result=simpleMath.getFactorial(0);
    expect(result).toEqual(0);
  }); 

  it("should calculate a factorial for -3 - which will raise an error", function() {
  expect(
    function() {
      simpleMath.getFactorial(-3)
    }).toThrow("Cannot be less than zero");
  }); 

});

The run and failure:

3 specs, 1 failure
Spec List | Failures
SimpleMath should calculate a factorial for -3 - which will raise an error
Expected function to throw 'Cannot be less than zero', but it threw Error: Cannot be less than zero.

I tried adding a period to the end of the message as the output shows that but it didn't help.

1 Answers
Related