Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Expectations in Jasmine

I have the following function which works

function sum ()
{
    var total = 0,
        num = 0,
        numArgs = arguments.length;

    if (numArgs === 0) {
        throw new Error("Arguments Expected");
    }

    for(var c = 0; c < numArgs; c += 1) {
        num = arguments[c];
        if (typeof(num) !== "number") {
            throw new Error("Only number are allowed but found", typeof (num));
        }
        total += num;

    }

    return total;

}


sum(2, "str"); // Error: Only number are allowed but found "string"

The jasmine spec file is the following:

describe("First test; example specification", function () {
    it("should be able to add 1 + 2", function (){
        var add = sum(1, 2);
        expect(add).toEqual(3);
    });
    it("Second Test; should be able to catch the excption 1 +'s'", function (){
        var add = sum(1, "asd");
        expect(add).toThrow(new Error("Only number are allowed but found", typeof("asd")));
    });
});

The fist test works great, for the second one I get a failing test.
How should I handle the expected error in Jasmine?

like image 552
underscore666 Avatar asked Apr 19 '12 17:04

underscore666


1 Answers

As discussed in this question, your code does not work because you should pass a function object to expect rather than the result of calling fn()

    it("should be able to catch the excption 1 +'s'", function (){
//        var add = sum(1, "asd");
        expect(function () {
            sum(1, "asd");
        }).toThrow(new Error("Only number are allowed but found", typeof ("asd")));
    });
like image 72
antonjs Avatar answered Nov 13 '22 11:11

antonjs