Why is Jasmine failing my pickup and breaking the bug?
I raise the same error I'm trying to catch but won't catch it
My code:
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 work, but the last one, which throws an exception, doesn't work:
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");
});
});
Startup and crash:
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 post as the output shows this, but it didn't help.
+3
source to share
1 answer
Since you are using toThrow()
, you must create an instance Error
:
expect(
function() {
simpleMath.getFactorial(-3)
}).toThrow(new Error("Cannot be less than zero"));
});
You can also use toThrowError()
which allows you to validate the message without the error type:
expect(
function() {
simpleMath.getFactorial(-3)
}).toThrowError("Cannot be less than zero");
});
+4
source to share