34

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?

mck
  • 1,334
  • 2
  • 12
  • 20
  • Did you try it? The documentation seems to imply that it would work. http://chaijs.com/api/bdd/#include – Schleis Jul 09 '13 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 Jul 09 '13 at 21:45

3 Answers3

37

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 })
random-forest-cat
  • 33,652
  • 11
  • 120
  • 99
26

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})
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
26

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.

Aleksey Solovey
  • 4,153
  • 3
  • 15
  • 34
Jyothi
  • 261
  • 3
  • 2