大家好。我正在學習茉莉花來測試我的角度應用程序。
我已經創建了一個基本函數,它可以乘以兩個數字。 如果給出的參數不是數字,則該函數會拋出錯誤。
然後我做了兩個非常基本的測試。
第一個檢查函數是否正確地乘以數字。 第二個檢查函數是否正確地拋出一個錯誤,如果給出一個字符串作爲參數。
第一次測試通過,第二次沒有。我不明白爲什麼。
的代碼:
功能:
function Multiply(num1, num2)
{
var result;
if (isNaN(num1) || isNaN(num2))
{
throw new Error("not a number");
}
else
{
result = num1 * num2;
return result;
}
}
該規範:
describe('The function', function()
{
it('properly multiply two numbers', function()
{
result = Multiply(10, 5);
expect(result).toEqual(50);
});
it('throw an error if a parameter is not a number', function()
{
result = Multiply(10, 'aaaa');
expect(result).toThrow(new Error("not a number"));
});
});
輸出:
2 specs, 1 failure
Spec List | Failures
The function throw an error if a parameter is not a number
Error: not a number
Error: not a number
at Multiply (http://localhost/jasmine_test/src/app.js:8:9)
如果我理解正確的茉莉花。這兩個測試都應該通過,因爲在第二種情況下,函數按我們的預期拋出錯誤。
問題:
如何測試是否正常運行拋出一個錯誤?
編輯:
我想這個新的代碼,但仍然沒有工作:
describe('The function', function()
{
it('throw an error if a parameter is not a number', function()
{
expect(function() { Multiply(10, 'aaaa') }).toThrowError(new Error("not a number"));
});
});
OUTPUT:
2 specs, 1 failure
Spec List | Failures
The function throw an error if a parameter is not a number
Error: Expected is not an Error, string, or RegExp.
中看到可用的錯誤匹配語法。您需要在作爲「expect」參數傳遞的匿名函數中運行它。 'expect(function(){Multiply(10,'aaaa')})' - 否則茉莉花沒有機會捕獲它 – zerkms
您需要'.toThrowError(錯誤,「而不是數字」)'。更新了我的答案。 – lonelyelk