For some test scenarios I run into the need of testing against multiple values which are all OK.
What I would like to do is something as follows:
expect(resultCode).toBeIn([200,409]);
This spec should pass when resultCode
is either 200
or 409
. Is that possible?
ADDED Thanks to peter and dolarzo for pointing me towards creating matchers. I had problems with addMatchers(). So, in the end I added the following to the jasmine.js:
jasmine.Matchers.prototype.toBeIn = function (expected) {
for (var i = 0; i < expected.length; i++)
if (this.actual === expected[i])
return true;
return false;
};
This gave me a working solution. I can now do the toBeIn as needed. (Jasmine 1.3.1)
In order to make something like this work:
expect(3).toBeIn([6,5,3,2]);
Jasmine has a feature called matchers:
This is an example on how to declare them. I have declared at the very end the method you are looking for:
describe('Calculator', function(){
var obj;
beforeEach(function(){
//initialize object
obj = new Object();
jasmine.addMatchers({
toBeFive: function () {
return {
compare: function (actual, expected) {
return {
pass: actual === 5,
message: actual + ' is not exactly 5'
}
}
};
},
toBeBetween: function (lower,higher) {
return {
compare: function (actual, lower,higher) {
return {
pass: ( actual>= lower && actual <= higher),
message: actual + ' is not between ' + lower + ' and ' + higher
}
}
};
},
toBeIn: function(expected) {
return {
compare: function (actual, expected) {
return {
pass: expected.some(function(item){ return item === actual; }),
message: actual + ' is not in ' + expected
}
}
};
}
});
});
This is the matcher you need:
toBeIn: function(expected) {
return {
compare: function (actual, expected) {
return {
pass: expected.some(function(item){ return item === actual; }),
message: actual + ' is not in ' + expected
}
}
};
}
Important with jasmine 2.0. I had to use jasmine.addMatchers({ with jasmine specrunner.html but when I configured it with Karma I had to replace jasmine with this like this.addMatchers({ because Karma use an earlier version of Jasmine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With