Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chai - Testing for values in array of objects

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

like image 355
Jared Yach Avatar asked Jan 18 '17 17:01

Jared Yach


People also ask

How do you compare two objects in Chai?

You can use deep-equal-in-any-order plugin. Chai plugin to match objects and arrays deep equality with arrays (including nested ones) being in any order. It works in a similar way as deep. equal but it doesn't check the order of the arrays (at any level of nested objects and arrays).

What is chai in testing?

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

Which assertion styles are considered BDD style in testing?

BDD. The BDD style comes in two flavors: expect and should . Both use the same chainable language to construct assertions, but they differ in the way an assertion is initially constructed.

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.


2 Answers

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'); 
like image 156
user2263572 Avatar answered Sep 23 '22 07:09

user2263572


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'}); 
like image 20
kub1x Avatar answered Sep 19 '22 07:09

kub1x