簡體   English   中英

如何使用Jasmine聲明異常?

[英]How to assert for an exception using 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

我的異常類:

function Exception(exceptionName, exceptionMessage) {

    var name = exceptionName;
    var message = exceptionMessage;

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

我究竟做錯了什么?

我會把它分成多個測試。

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

    });

});

異常斷言僅適用於與Javascript內置Error類實例一起使用的情況。 我使用自己定義的Exception()類,這就是問題的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM