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?
In Chai. js, the equal assertion, along with most other included Chai assertions, uses Javascipt's strict equality. During testing, it often is the case that strict equality is not desired, but instead equality in the sense that two objects are “equivalent” in that they have the same content.
var assert = require('chai'). assert , foo = 'bar' , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] }; assert. typeOf(foo, 'string'); // without optional message assert. typeOf(foo, 'string', 'foo is a string'); // with optional message assert.
Chai is such an assertion library, which provides certain interfaces to implement assertions for any JavaScript-based framework. Chai's interfaces are broadly classified into two: TDD styles and BDD styles.
Mocha is a JavaScript test framework running on Node. js and in the browser. Mocha allows asynchronous testing, test coverage reports, and use of any assertion library. Chai is a BDD / TDD assertion library for NodeJS and the browser that can be delightfully paired with any javascript testing framework.
Here is an alternative and non order dependent approach for collections:
expect([1, 2, 3]).to.include.members([3, 2, 1])
You can also use this with a deep
flag for comparison of objects:
expect([{ id: 1 }]).to.deep.include.members([{ id: 1 }]);
expect({foo: 'bar', width: 190, height: 90}).to.include({ height: 90, width: 190 })
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})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With