Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 475
BentOnCoding Avatar asked Mar 04 '13 19:03

BentOnCoding


People also ask

How do I add a custom matcher to Jasmine?

Custom Matchers describe('This custom matcher example', function() { beforeEach(function() { // We should add custom matched in beforeEach() function. jasmine. addMatchers ({ validateAge: function() { Return { compare: function(actual,expected) { var result = {}; result. pass = (actual > = 13 && actual < = 19); result.

Which of the following Jasmine matchers can be used for matching a regular expression?

It checks whether something is matched for a regular expression. You can use the toMatch matcher to test search patterns.


2 Answers

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

like image 114
Xotabu4 Avatar answered Sep 28 '22 11:09

Xotabu4


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

like image 29
Andreas Köberle Avatar answered Sep 28 '22 10:09

Andreas Köberle