tôi thay thế matcher của Jasmine's toThrow bằng phần sau, cho phép bạn so khớp thuộc tính tên của exception hoặc thuộc tính message của nó. Đối với tôi điều này làm cho các bài kiểm tra dễ dàng hơn để viết và ít giòn, như tôi có thể làm như sau:
throw {
name: "NoActionProvided",
message: "Please specify an 'action' property when configuring the action map."
}
và sau đó kiểm tra như sau:
expect (function() {
.. do something
}).toThrow ("NoActionProvided");
này cho phép tôi tinh chỉnh thông điệp ngoại lệ sau mà không vi phạm kiểm tra, khi điều quan trọng là nó ném loại ngoại lệ dự kiến.
Đây là sự thay thế cho toThrow cho phép này:
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;
};
Để vượt qua đối số chức năng đang được thử nghiệm, mà không sử dụng một chức năng ẩn danh, hãy thử 'Function.bind': http://stackoverflow.com/ a/13233194/294855 –