Checking all elements of an array with chai

When testing with mocha and tea, I often need to check if all the elements in an array satisfy a condition.

I am currently 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 that provides this behavior. Am I missing something or will I have to write a plugin for chai extension?

+3


source to share


3 answers


There may not be much improvement over your current approach, but you can do something like:



expect(a).to.satisfy(function(nums) { 
    return nums.every(function(num) {
        return num instanceof Number;
    }); 
});

      

+7


source


Check out Chai Things , this is a Chai plugin designed to improve support for arrays.

Example:



[1, 2, 3].should.all.be.a('number')

+3


source


as a result of adding the above two answers with satisfy and chai-things

a.should.all.satisfy(s => typeof(s) === 'number');

      

as an option for some cases you can 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);

      

0


source







All Articles