Chai - Testing for values in array of objects

后端 未结 6 1299
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 12:22

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\', de         


        
6条回答
  •  执念已碎
    2021-01-01 12:55

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

提交回复
热议问题