Chai - Testing for values in array of objects

As stated here following code works now with [email protected] and chai-things. I just love the natural readability of this approach.

var chai = require('chai'),
    expect = chai.expect;

chai.use(require('chai-like'));
chai.use(require('chai-things')); // Don't swap these two

expect(data).to.be.an('array').that.contains.something.like({title: 'Blah'});

This is what I usually do within the test:

var result = query_result;

var members = [];
result.forEach(function(e){
    members.push(e.title);
});

expect(members).to.have.members(['expected_title_1','expected_title_2']);

If you know the order of the return array you could also do this:

expect(result).to.have.deep.property('[0].title', 'expected_title_1');
expect(result).to.have.deep.property('[1].title', 'expected_title_2');

ES6+

Clean, functional and without dependencies, simply use a map to filter the key you want to check

something like:

const data = [{_id: 5, title: 'Blah', owner: 'Ted', description: 'something'},{_id: 70, title: 'GGG', owner: 'Ted', description: 'something'}];


expect(data.map(e=>({title:e.title}))).to.include({title:"Blah"});

or even shorter if you only check one key:

expect(data.map(e=>(e.title))).to.include("Blah");

https://www.chaijs.com/api/bdd/


Probably the best way now a days would be to use deep.members property

This checks for unordered complete equality. (for incomplete equality change members for includes)

i.e.

expect([ {a:1} ]).to.have.deep.members([ {a:1} ]); // passes
expect([ {a:1} ]).to.have.members([ {a:1} ]); // fails

Here is a great article on testing arrays and objects https://medium.com/building-ibotta/testing-arrays-and-objects-with-chai-js-4b372310fe6d

DISCLAIMER: this is to not only test the title property, but rather a whole array of objects