Counting records in JSON array using javascript and Postman

Chrissi picture Chrissi · Mar 14, 2016 · Viewed 54.7k times · Source

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.

Answer

RC_02 picture RC_02 · Mar 6, 2017

In postman, under Tests section, do the following (screenshot below): var body = JSON.parse(responseBody); tests["Count: " + body.value.length] = true;

Here is what you should see (note: I replaced responseBody with JSON to mock up example above): enter image description here