Reputation: 1721
When testing with Mocha and Chai, I often need to test whether all the elements in an array satisfy a condition.
Currently I'm using something like the following:
var predicate = function (el) {
return el instanceof Number;
};
it('Should be an array of numbers', function () {
var success, a = [1, 2, 3];
success = a.every(predicate);
expect(success).to.equal(true);
});
Looking through the docs, I can't immediately see anything which provides this kind of behavior. Am I missing something or will I have to write a plugin to extend chai?
Upvotes: 7
Views: 13606
Reputation: 2611
Take a look at Chai Things, it's a plugin for Chai that is meant to improve support for arrays.
Example:
[1, 2, 3].should.all.be.a('number')
Upvotes: 8
Reputation: 1213
as result of adding two above answers with satisfy and chai-things
a.should.all.satisfy(s => typeof(s) === 'number');
as variant for some cases you may also use something like this
a.filter(e => typeof(e)==='number').should.have.length(a.length);
a.filter(e => typeof(e)==='number').should.eql(a);
Upvotes: 2
Reputation: 14053
Might not be a big improvement over your current approach, but you could do something like:
expect(a).to.satisfy(function(nums) {
return nums.every(function(num) {
return num instanceof Number;
});
});
Upvotes: 8