如何使用Jasmine声明异常?

时间:2013-05-15 18:09:19

标签: javascript jasmine

我正在尝试编写一个测试来确保我正在执行的无效实例化会产生异常。测试如下:

describe('Dialog Spec', function () {
"use strict";

it("should throw an exception if called without a container element", function () {
    expect(function() {
        new Dialog({});
    }).toThrow(new Exception("InvalidArgumentException", "Expected container element missing"));
  });
});

Dialog()类:

function Dialog(args) {

    if (undefined === args.containerElement)
        throw new Exception("InvalidArgumentException", "Expected container element missing");

    this.containerElement = args.containerElement;

  }
}

我在茉莉花中遇到了以下失败。

Expected function to throw Exception InvalidArgumentException: Expected container element missing , but it threw Exception InvalidArgumentException: Expected container element missing

My Exception class:

function Exception(exceptionName, exceptionMessage) {

    var name = exceptionName;
    var message = exceptionMessage;

    this.toString = function () {
        return "Exception " + name + ": "+ message;
    };
}

我做错了什么?

2 个答案:

答案 0 :(得分:4)

我会把它分成多个测试。

describe("creating a new `Dialog` without a container element", function() {

    it("should throw an exception", function () {
        expect(function() {
            new Dialog({});
        }).toThrow(new Exception("InvalidArgumentException", "Expected container element missing"));
    });

    describe("the thrown exception", function() {

        it("should give a `InvalidArgumentException: Expected container element missing` message", function () {
            try {
                new Dialog({});
                expect(false).toBe(true); // force the text to fail if an exception isn't thrown.
            }
            catch(e) {
                expect(e.toString()).toEqual("InvalidArgumentException: Expected container element missing");
            }
        });

    });

});

答案 1 :(得分:3)

异常断言仅适用于与Javascript内置Error类实例一起使用的情况。我使用自己定义的Exception()类,这就是问题的原因。