我提出了我试图捕获但未捕获的相同错误
我的代码是:
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);
}
}
我的测试如下。前 2 个有效,但引发异常的最后一个失败:
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");
});
});
运行与失败:
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.
我尝试在消息末尾添加句点,因为输出显示如此,但没有帮助。
最佳答案
由于您正在使用 toThrow()
,因此您应该实例化一个 Error
实例:
expect(
function() {
simpleMath.getFactorial(-3)
}).toThrow(new Error("Cannot be less than zero"));
});
您还可以使用 toThrowError()
允许检查没有错误类型的消息:
expect(
function() {
simpleMath.getFactorial(-3)
}).toThrowError("Cannot be less than zero");
});
关于javascript - 为什么 Jasmine 在我提出并捕获错误时失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44052830/