Javascript 如何使用Jasmine断言异常?
我正在尝试编写一个测试,以确保我正在执行的无效实例化产生异常。测试如下:Javascript 如何使用Jasmine断言异常?,javascript,jasmine,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
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()类:
我在《茉莉花》中失败了
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");
}
});
});
});
exception的断言仅在与Javascript内置错误类实例一起使用时有效。我使用自己定义的Exception()类,这就是问题的原因 第二个测试的问题是
expect
在catch块中。如果在调用newdialog({})
时更改了代码并且没有引发异常,那么即使功能已中断,测试也将通过!这就是为什么会有第一个测试,@VarunAchar
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");
}
});
});
});