为什么Jasmine失败了我的提升和捕获错误?

时间:2017-05-18 16:07:55

标签: javascript jasmine

我提出了同样的错误,我试图捕捉但没有抓住它

我的代码是:

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);
  }
}

我的测试如下。前两个工作,但最后一个提出异常失败:

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.

我尝试在邮件末尾添加一个句点,因为输出显示但是它没有帮助。

1 个答案:

答案 0 :(得分:4)

由于您使用的是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");
});