How to pass a custom error message to a jasmine matcher?
If you take a look at the jasmine source code you will see that there is no way to set the message from outside a matcher. For example the toBeNaN
matcher.
/**
* Matcher that compares the actual to NaN.
*/
jasmine.Matchers.prototype.toBeNaN = function() {
this.message = function() {
return [ "Expected " + jasmine.pp(this.actual) + " to be NaN." ];
};
return (this.actual !== this.actual);
};
As you can see the messages is hard coded into the matcher and will be set when you call the matcher. The only way I can think off to have your own messages is to write your matcher like described here
This issue is tracking interest in implementing custom error messages using a .because()
mechanism.
In the meantime, avrelian has created a nice library which implements custom error messages using a since()
mechanism – jasmine-custom-message
.
Yes, it can be done.
You may define a custom matcher in global scope, overriding the error message in jasmine as below:
beforeEach(function () {
jasmine.addMatchers({
toReport: function () {
return {
compare: function (actual, expected, msg) {
var result = {pass: actual == expected};
result.message = msg;
return result;
}
}
}
});
});
Update 2022; Use .withContext(...)
method instead of below (as optional parameter is deprecated).
Jasmine already supports optional parameter in all matchers (toBe, toContain, and others), so you can use:
expect(true).toBe(false, 'True should be false').
Then in output it will look like this:
Message:
Expected true to be false, 'True should be false'.
Link to commit (this is not described in documentation): https://github.com/ronanamsterdam/DefinitelyTyped/commit/ff104ed7cc13a3eb2e89f46242c4dbdbbe66665e