Counting records in JSON array using javascript and Postman

Viewed 85805

I have a control that returns 2 records:

{
  "value": [
    {
      "ID": 5,
      "Pupil": 1900031265,
      "Offer": false,
    },
    {
      "ID": 8,
      "Pupil": 1900035302,
      "Offer": false,
      "OfferDetail": ""
    }
  ]
}

I need to test via Postman, that I have 2 records returned. I've tried various methods I've found here and elsewhere but with no luck. Using the code below fails to return the expected answer.

responseJson = JSON.parse(responseBody);
var list = responseBody.length;
tests["Expected number"] = list === undefined || list.length === 2;

At this point I'm not sure if it's the API I'm testing that's at fault or my coding - I've tried looping through the items returned but that's not working for me either. Could someone advise please - I'm new to javascript so am expecting there to be an obvious cause to my problem but I'm failing to see it. Many thanks.

11 Answers

Here's the simplest way I figured it out:

pm.expect(Object.keys(pm.response.json()).length).to.eql(18);

No need to customize any of that to your variables. Just copy, paste, and adjust "18" to whatever number you're expecting.

This is what I did for counting the recods

//parsing the Response body to a variable
    responseJson = JSON.parse(responseBody);

//Finding the length of the Response Array
    var list = responseJson.length;
    console.log(list);
    tests["Validate service retuns 70 records"] = list === 70;

enter image description here

More updated version of asserting only 2 objects in an array:

pm.test("Only 2 objects in array", function (){
    pm.expect(pm.response.json().length).to.eql(2);
});

First of all you should convert response to json and find value path. Value is array. You should call to length function to get how many objects in there and check your expected size

pm.test("Validate value count", function () {
    pm.expect(pm.response.json().value.length).to.eq(2);
});

I had a similar problem, what I used to test for a certain number of array members is:

responseJson = JSON.parse(responseBody);
tests["Response Body = []"] = responseJson.length === valueYouAreCheckingFor;

To check what values you're getting, print it and check the postman console.

console.log(responseJson.length);

Working Code

 pm.test("Verify the number of records",function()
 {
   var response = JSON.parse(responseBody); 
   pm.expect(Object.keys(response.value).length).to.eql(5);

 });
//Please change the value in to.eql function as per your requirement    
//'value' is the JSON notation name for this example and can change as per your JSON
Related