Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 562
FrancescoMussi Avatar asked Dec 12 '22 01:12

FrancescoMussi


1 Answers

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.

like image 130
Scott Sellers Avatar answered Dec 18 '22 12:12

Scott Sellers