我将 Jasmine 的 toThrow 匹配器替换为以下内容,它允许您匹配异常的 name 属性或其 message 属性。对我来说,这使测试更容易编写并且不那么脆弱,因为我可以执行以下操作:
throw {
name: "NoActionProvided",
message: "Please specify an 'action' property when configuring the action map."
}
然后使用以下内容进行测试:
expect (function () {
.. do something
}).toThrow ("NoActionProvided");
这让我稍后可以在不中断测试的情况下调整异常消息,重要的是它抛出了预期的异常类型。
这是 toThrow 的替代品,它允许这样做:
jasmine.Matchers.prototype.toThrow = function(expected) {
var result = false;
var exception;
if (typeof this.actual != 'function') {
throw new Error('Actual is not a function');
}
try {
this.actual();
} catch (e) {
exception = e;
}
if (exception) {
result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected) || this.env.equals_(exception.name, expected));
}
var not = this.isNot ? "not " : "";
this.message = function() {
if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) {
return ["Expected function " + not + "to throw", expected ? expected.name || expected.message || expected : " an exception", ", but it threw", exception.name || exception.message || exception].join(' ');
} else {
return "Expected function to throw an exception.";
}
};
return result;
};