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?
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?
Share Improve this question edited Nov 19, 2020 at 14:33 Penny Liu 17.4k5 gold badges86 silver badges108 bronze badges asked Jul 21, 2015 at 12:08 StickyCubeStickyCube 1,7212 gold badges17 silver badges22 bronze badges3 Answers
Reset to default 8Might 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;
});
});
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')
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);