Chai - Testing for values in array of objects

Jared Yach picture Jared Yach · Jan 18, 2017 · Viewed 37.2k times · Source

I am setting up my tests for the results to a REST endpoint that returns me an array of Mongo database objects.

[{_id: 5, title: 'Blah', owner: 'Ted', description: 'something'...},
 {_id: 70, title: 'GGG', owner: 'Ted', description: 'something'...}...]

What I want my tests to verify is that in the return array it conatins the specific titles that should return. Nothing I do using Chai/Chai-Things seems to work. Things like res.body.savedResults.should.include.something.that.equals({title: 'Blah'}) error out I'm assuming since the record object contains other keys and values besides just title.

Is there a way to make it do what I want? I just need to verify that the titles are in the array and don't care what the other data might be (IE _id).

Thanks

Answer

user2263572 picture user2263572 · Jan 18, 2017

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');