Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocha, Chai: Assert that Object is included in an Array of Objects

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?

like image 463
mck Avatar asked Jul 09 '13 21:07

mck


People also ask

What is Chai's assertion style to compare the contents of objects?

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.

How do you assert chai?

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.

What assertion styles are present in Chai testing assertion library?

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.

What is mocha chai?

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.


3 Answers

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 })
like image 54
lfender6445 Avatar answered Oct 12 '22 17:10

lfender6445


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})
like image 25
Andreas Köberle Avatar answered Oct 12 '22 19:10

Andreas Köberle


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.

like image 25
Jyothi Avatar answered Oct 12 '22 19:10

Jyothi