Reputation: 5752
I'm using chai.js
expectations with the mocha JS test framework. I'm trying to test inclusion of objects in arrays but it appears the includes
behavior supported by chai in their documentation doesn't work as I expect:
The example on the chai website says this:
expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2});
That works as expected. However, the following fails:
expect([{a: 1}]).to.be.an('array').and.include({a: 1})
with the error:
(node:5639) ... AssertionError: expected [ { a: 1 } ] to include { a: 1 }
But this succeeds:
expect([1,2]).to.be.an('array').and.include(1)
What am I doing wrong?
Upvotes: 1
Views: 1820
Reputation: 23859
As per the docs:
When the target is an array,
.include
asserts that the givenval
is a member of the target.
Clearly, the member of the array [{a: 1}]
and the matchee {a: 1}
are two different objects. Thus the matchee is not a member of the target. On the other hand, primitives are matched using their values, instead of their references. Hence the following assertion passes:
expect([1,2]).to.be.an('array').and.include(1)
And for the object, the docs say:
When the target is an object,
.include
asserts that the given objectval
’s properties are a subset of the target’s properties.
This means that chai actually checkes for the value similarity of each property between both the objects. That's why the assertion passes there as well.
To correct this, you can declare the variable once, and use it at both the places:
var obj = {a: 1};
expect([obj]).to.be.an('array').and.include(obj);
Or, you can deep check in the target array like this:
expect([{a: 1}]).to.deep.include({a: 1});
Upvotes: 1