断言所有数组元素都是对象

时间:2015-07-16 06:54:27

标签: chai should.js

如何断言列表的所有元素都是对象?

should.exist(list)

list.should.be.an('array')

... // ?

1 个答案:

答案 0 :(得分:0)

如果我们谈论should,您可以使用这样的方法:

> var should = require('./');
> var list1 = [1, 2, 3];
> var list2 = [1, { a: 10}, 3];
> var list3 = [{ a: 11}, {b: 10}];
> list1.should.matchEvery(function(it) { return it.should.be.an.Object(); });
AssertionError: expected Array [ 1, 2, 3 ] to match each Function { name: '' }
    expected 1 to match Function { name: '' }
        expected 1 to be an object
            expected 1 to have type object
                expected 'number' to be 'object'
    at Assertion.fail (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:180:17)
    at Assertion.prop.value (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:65:17)
    ...

> list2.should.matchEvery(function(it) { return it.should.be.an.Object(); });
AssertionError: expected Array [ 1, Object { a: 10 }, 3 ] to match each Function { name: '' }
    expected 1 to match Function { name: '' }
        expected 1 to be an object
            expected 1 to have type object
                expected 'number' to be 'object'
    at Assertion.fail (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:180:17)
    at Assertion.prop.value (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:65:17)
    ...

> list3.should.matchEvery(function(it) { return it.should.be.an.Object(); });
{ obj: [ { a: 11 }, { b: 10 } ],
  anyOne: false,
  negate: false,
  params: 
   { operator: 'to match each Function { name: \'\' }',
     message: undefined } }
> 

所以我使用了.matchEvery并检查了每个元素是否为对象。您可以参考api docs了解更多示例。