Jasmine中的错误期望

und*_*666 10 javascript testing jasmine

我有以下功能可行

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"
Run Code Online (Sandbox Code Playgroud)

茉莉花规格文件如下:

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")));
    });
});
Run Code Online (Sandbox Code Playgroud)

第一次测试效果很好,第二次测试失败了.
我该如何处理预期的错误Jasmine

ant*_*njs 16

正如在这个问题中讨论的那样,你的代码不起作用,因为你应该传递一个函数对象而不是调用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")));
    });
Run Code Online (Sandbox Code Playgroud)