Custom matcher for testing with Jasmine

08 / Jul / 2015 by Mohit Tyagi 1 comments

Jasmine is a behavior-driven development framework for testing JavaScript code. Many Jasmine users only use the default set of matchers which are extremely powerful, yet are unable to meet our requirements when dealing with complicated or custom code.

Jasmine provides a wide list of built-in matchers:

Arrays:
[javascript]
expect(array).toBeArray();
expect(array).toBeArrayOfNumbers();
expect(array).toBeEmptyArray();[/javascript]

Booleans:
[javascript]
expect(boolean).toBeBoolean();
expect(boolean).toBeFalse();
expect(boolean).toBeTrue();[/javascript]

Mix:
[javascript]
expect(instance).toBe(instance);
expect(number).toBeGreaterThan(number);
expect(number).toBeLessThan(number);
expect(mixed).toBeNull();
expect(mixed).toBeUndefined();[/javascript]

We can use these matchers in our test cases like this:

[javascript]
it(‘Test case description’, function() {
var status = true;
expect(status).toBeTrue(); // This will pass
expect(status).toBeFalse(); // this will fail
});
[/javascript]

Not only that, we can also create our own custom matcher and publish it in the community so that other users can also use it. We can write simple functions that will work as matchers.
Let’s see, how we can do this:

[javascript]
describe(‘custom matchers demo’, function() {
beforeEach(function() {
// register these matchers before each test cases. Once a custom matcher is registered with Jasmine, it is available on any test case.
jasmine.addMatchers({
toBeValidAge: function() {
return {
compare: function(actual, expected) {
//compare function that takes an actual value and expected value.
// expect(10).matcher(20); actual will be 10 and expected will be 20.
var result = {};
result.pass = (actual >=18 && actual <=35);
// Our custom logic goes here.
result.message = actual + ‘ is not valid age for this job’;
// This will be shown when test get failed
return result;
//The compare function must return a result object with:
// 1. A ‘pass’ property that is a boolean result of the matcher
// 2. A ‘message’ property that is a string to show details when test get failed.
}
};
}
});
});

// First test
it(‘age should be valid for this job’, function() {
var myAge = 23;
expect(myAge).toBeValidAge();
// return true if test will pass
});

// Second test
it(‘age should be valid for this job’, function() {
var yourAge = 15;
expect(yourAge).toBeValidAge();
// return false if test will fail
});
});[/javascript]

In line 13 we have customized our error messages to display the following message: ‘age’ is not valid age for this job.

This happens because the second test fails as the passed age ’15’ is not between ’18’ and ’35’ in the above example.

Happy Testing 🙂

FOUND THIS USEFUL? SHARE IT

comments (1 “Custom matcher for testing with Jasmine”)

  1. Pingback: Testing promises with Jasmine | TO THE NEW Blog

Leave a Reply

Your email address will not be published. Required fields are marked *