2017-05-18 7 views
3

私は私がキャッチしようとしていますが、私のコードはそれをジャスミンが私の持ち上げに失敗してエラーをキャッチするのはなぜですか?

をキャッチなく、同じエラーも募集中です:

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点の作品が、例外を発生させ、最後の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. 

いるが、それは助けになりませんでした。

答えて

4

あなたがtoThrow()を使用しているので、あなたはErrorインスタンスインスタンス化する必要があります。

expect(
    function() { 
    simpleMath.getFactorial(-3) 
    }).toThrowError("Cannot be less than zero"); 
}); 
+0

はい:また、エラータイプなしでメッセージを確認することができますtoThrowError()を使用することができます

expect( function() { simpleMath.getFactorial(-3) }).toThrow(new Error("Cannot be less than zero")); }); 

を。私のJavascriptユニットテストブックにはいくつかのエラーがあります。 –

関連する問題