SCENARIO:
Hey everyone! I'm currently diving into Jasmine to test my Angular application.
I've created a simple function that multiplies two numbers. If the input parameters are not numbers, the function throws an error.
Next, I wrote two basic tests:
The first one checks if the function correctly multiplies the numbers, and the second one verifies if the function correctly throws an error when a string is provided as a parameter.
The first test passed successfully, but the second one failed. I'm puzzled about the reason for the failure.
CODE SNIPPET:
The function:
function Multiply( num1, num2 )
{
var result;
if (isNaN(num1) || isNaN(num2))
{
throw new Error("not a number");
}
else
{
result = num1 * num2;
return result;
}
}
The spec:
describe('The function', function ()
{
it('correctly multiplies two numbers', function ()
{
result = Multiply(10, 5);
expect(result).toEqual(50);
});
it('throws an error if a parameter is not a number', function ()
{
result = Multiply(10, 'aaaa');
expect(result).toThrow(new Error("not a number"));
});
});
TEST RESULTS:
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)
As far as I understand Jasmine, both tests should pass since the function throws the error as expected in the second test.
QUESTION:
How can I accurately test if a function correctly throws an error?
EDIT:
I attempted this new code, but it still isn't working:
describe('The function', function ()
{
it('throws 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.