johnnyfittizio johnnyfittizio - 9 days ago 7
AngularJS Question

Jasmine - How to test errors?

THE SITUATION:

Hello guys. I am learning jasmine to test my angular app.

I have create a basic function that does multiply two numbers.
If the parameters given are not a number, the function throw an error.

I then made two very basic tests.

The first to check if the function properly multiply the numbers.
The second to check if the function properly throw an error if a string is given as parameter.

The first test pass, the second not. And i don't understand why.

THE CODE:

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('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"));

});

});


THE OUTPUT:

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)


If i understand properly Jasmine. Both test should pass, because in the second case the function throw the error as we expected.

THE QUESTION:

How can i test if a function properly throw an error?




EDIT:

I am trying this new code, but is still not working:

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.

Answer

If I understand correctly you need to pass a function into the expect(...) call.

The code you have here:

expect(result).toThrow(new Error("not a number"));

Is checking the result of Multiply, which when it works is fine, but like I said .toThrow() expects a function, I'd use an anonymous function instead, see below:

expect( function(){ Multiply(10, 'aaaa'); } ).toThrow(new Error("not a number"));

EDIT: Did a quick search and this blog post is a very detailed explanation of what I am trying to say.

Comments