最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Checking all elements in an Array with Chai - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 8

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;
    }); 
});

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);
发布评论

评论列表(0)

  1. 暂无评论