Chai - Testing for values in array of objects

我的梦境 提交于 2019-11-30 11:37:22
user2263572

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

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

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