我将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;
};
Function.bind
:stackoverflow.com/a/13233194/294855