Chai - Testing for values in array of objects

梦想的初衷 提交于 2019-11-29 17:09:34

问题


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


回答1:


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



回答2:


As stated here following code works now with chai-like@0.2.14 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'});



回答3:


An alternative solution could be extending the array object with a function to test if an object exists inside the array with the desired property matching the expected value, like this

/**
 * @return {boolean}
 */
Array.prototype.HasObjectWithPropertyValue = function (key, value) {
    for (var i = 0; i < this.length; i++) {
        if (this[i][key] === value) return true;
    }
    return false;
};

(i put this in my main test.js file, so that all other nested tests can use the function)

Then you can use it in your tests like this

var result = query_result;
// in my case (using superagent request) here goes
// var result = res.body;

result.HasObjectWithPropertyValue('property', someValue).should.equal(true);


来源:https://stackoverflow.com/questions/41726208/chai-testing-for-values-in-array-of-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!