Search code examples
arraysjsonpostmanpostman-testcase

How to write a test for nested JSON response from enterprise application


I'm trying to use Postman as a test tool to validate that our customers all have a mailing address in our master system. I'm having trouble drilling down into the JSON due to its structure. Each response is an array structure with a single "node" that has no "head attribute" to address.

Example JSON:


[
  {
    "ID": "cmd_org_628733899",
    "organization": {
      "name": "FULL POTENTIAL",
      "accountStatusCode": "1",
      "accountStatusDescription": "OPEN"
    },
    "location": [
      {
        "locality": "LITTLE ROCK",
        "locationType": "MAILING"
      },
      {
        "locality": "BIG ROCK",
        "locationType": "LOCATION"
      }
    ]
  }
]

Test code as it exists:

pm.test("Check for a Mailing Address", function () {
   // Parse response body
   var jsonData = pm.response.json();

   // Find the array index for the MAILING Address
   var mailingLocationIndex = jsonData.location.map(
          function(filter) {
             return location.locationType; 
          }
    ).indexOf('MAILING'); 

   // Get the mailing location object by using the index calculated above
   var mailingLocation = jsonData.location[mailingFilterIndex];

   // Check that the mailing location exists
   pm.expect(mailingLocation).to.exist;

});

Error message: TypeError: Cannot read property 'map' of undefined

I understand that I have to iterate to node(0) in the outer array and then drill into the nested location array to find an entry with a locationType = Mailing.

I can't get past the outer array. I'm new to JavaScript and JSON parsing - I am a COBOL programmer.


Solution

  • Knowing nothing else, I would say you mean this

    pm.test("Check for a Mailing Address", function () {
        var mailingLocations = pm.response.json().location.filter(function (item) {
            return item.locationType === 'MAILING';
        });
        pm.expect(mailingLocations).to.have.lengthOf(1);
    });
    

    You want to filter out all the locations that have a MAILING type and there should be exactly one, or at least one, depending.

    Whether pm.response.json() actually returns the object you show in your question is impossible to say from where I'm standing.


    In modern JS, the above is shorter:

    pm.test("Check for a Mailing Address", function () {
        var mailingLocations = pm.response.json().location.filter(item => item.locationType === 'MAILING');
        pm.expect(mailingLocations).to.have.lengthOf(1);
    });