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
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).
Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
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.
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.
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');
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'});
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