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

javascript - Mocha, Chai: Assert that Object is included in an Array of Objects - Stack Overflow

programmeradmin7浏览0评论

Chai has a nice way to assert if an Array includes a certain element

expect([1,2,3]).to.include(2);

What I would like is something similar, given an Array of Objects:

expect([{a:1},{b:2}]).to.include({b:2});

Is this possible?

Chai has a nice way to assert if an Array includes a certain element

expect([1,2,3]).to.include(2);

What I would like is something similar, given an Array of Objects:

expect([{a:1},{b:2}]).to.include({b:2});

Is this possible?

Share Improve this question asked Jul 9, 2013 at 21:24 mckmck 1,4042 gold badges13 silver badges22 bronze badges 2
  • Did you try it? The documentation seems to imply that it would work. chaijs.com/api/bdd/#include – Schleis Commented Jul 9, 2013 at 21:34
  • Yeah I tried -- those examples only show how to test if a certain key exists, not the actual value (or entire object for that matter) – mck Commented Jul 9, 2013 at 21:45
Add a comment  | 

3 Answers 3

Reset to default 39

Here is an alternative and non order dependent approach for collections:

array

expect([1, 2, 3]).to.include.members([3, 2, 1])

You can also use this with a deep flag for comparison of objects:

array of objects

expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }]);

object

expect({foo: 'bar', width: 190, height: 90}).to.include({ height: 90, width: 190 })

You can use deep method for the array of objects.

expect([{a:1},{b:2}]).to.deep.include({b:2});   //It will pass

You can find more examples using deep method here: http://chaijs.com/api/bdd/#method_deep

The main point to remember here is about reference types.

Take a look at the Chai Things plugin, that does what you want:

[{a:1},{b:2}].should.include.something.that.deep.equals({b:2})
发布评论

评论列表(0)

  1. 暂无评论