3

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

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

我的例外类:

function Exception(exceptionName, exceptionMessage) {

    var name = exceptionName;
    var message = exceptionMessage;

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

我究竟做错了什么?

4

2 回答 2

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");
            }
        });

    });

});
于 2013-05-15T18:15:49.240 回答
3

异常断言仅在与 Javascript 内置的 Error 类实例一起使用时才有效。我正在使用自己定义的 Exception() 类,这就是问题的原因。

于 2013-05-15T18:16:08.960 回答