For loop for retrieving a attribute value from response body

@rajshrees
This happened because you’re running a for loop 100 times and then you’re trying to access the i-th item of the array whereas your array probably doesn’t even have those items.

So, for example your sections array is of the length 10 but your for loop is checking sections[88] which is undefined and then you’re trying to access the name property of this undefined value.
That’s why you were getting the error.

Steps to fix :

  1. You can make use of safe extraction by using _.get which has been provided as a function by lodash. (lodash comes built-in with Postman)
    Docs: https://lodash.com/docs/4.17.11#get

  2. Don’t run the for loop for 100 times, just run it over all the items that you have in the sections array.

You can update your test script like this:

 var jsonData = JSON.parse(responseBody),
    i,
    // Extract out the sections array from the response that was recevied
    sections = _.get(jsonData, 'responses[0].getSectionsCategoriesItems.content.sections');

 // Run the for loop only over the items of the section, i.e uptil the section.length
 for (i = 0; i < sections.length; i++) {
     var sectionName = _.get(sections, `${i}.name`); // Safe extraction
     if (sectionName === "Hidden Categories Section") // use === instead of ==
         console.log("Test case Failed - Hidden category is retrieving in response");
     else
         console.log("Test case Passed - Hidden category is not retrieving in response")
 }
2 Likes