BentOnCoding BentOnCoding - 2 months ago 18
Javascript Question

How to pass a custom error message to a jasmine matcher?

In all the testing frameworks I have used, there is an optional parameter to specify you own custom error message.

This can be very useful, and I can't find a way to do this out of the box with jasmine.

I've had 3 other developers ask me about this exact functionality, and when it comes to jasmine I don't know what to tell them.

Is it possible to specify your own custom error message on each assertion ?


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