我是茉莉花的新手,非常抱歉,如果這是一個愚蠢的問題。爲什麼在用Jasmine測試異常時需要不同的語法?
我有一個這樣的測試...
it("should calculate factorial 5", function() {
expect(MathsUtils.fact(5)).toBe(120);
});
這工作得很好。如果你傳遞一個負數我其實函數拋出一個異常,所以我試圖測試有以下...
it("should throw an exception when passed -1", function() {
expect(MathsUtils.fact(-1)).toThrow("n! does not exist for negative numbers");
});
但是這並沒有。經過一番搜索,我發現如果我改變這個測試看起來像這樣...
it("should throw an exception when passed -1", function() {
expect(function() { MathsUtils.fact(-1); }).toThrow("n! does not exist for negative numbers");
});
......它通過。但是,如果我以類似的方式更改我的第一個測試...
it("should calculate factorial 5", function() {
expect(function() { MathsUtils.fact(5); }).toBe(120);
});
...它失敗。
爲什麼我需要兩種測試的不同語法?這兩者似乎都沒有爲另一方工作。
正如我所說的,我是茉莉花的新手,所以如果這在文檔中有介紹,請指向正確的方向,因爲我看不到任何解釋。
這就是它的實現方式,你只需要像這樣使用它。你嘗試過'toThrowError' –
因爲,**根據文檔**,*「'toThrow'匹配器用於測試函數是否拋出異常」*。否則,在實際調用* expect之前拋出異常*。 – jonrsharpe
@VictoryOsikwemhe我試圖給ThrowError,但那也失敗了。你有鏈接到文檔?謝謝 –