Search code examples
for-looppostmanpostman-collection-runner

For Loop in Postman not Working as Expected


I am trying to use Postman Runner and run through a JSON data file and get every record back from the data file in the console.

Currently I am only getting the first line back.

My JSON data file looks like this:

[
  {
    "line1": "13579",
    "line2": "2468",
    "line3": "1234",
    "line4": "5678",
  },
  {
    "line1": "13468",
    "line2": "2425",
    "line3": "12578",
    "line4": "567343",
  }
]

My code that I have tried is:

var res = JSON.parse(responseBody);

for (let i = 0; i < res.length; i++) {
  console.log("actual data: " + i + " = " + data[i].line1);

    // tests start
    pm.test("iteration: " + i + " = " + "expected line1 = " + data.line1 + " | Actual line1 = " + res[i].line1 , function () {
        pm.expect(res[i].line1).to.equal(data[i].line1);
    });
}

However, this prints out an error in the console:

"TypeError: Cannot read property 'line1' of undefined"

If I change this to console.log("actual data: " + i + " = " + data.line1);, it then writes out:

actual data: 0 = 13579
actual data: 1 = 13579
actual data: 2 = 13579

[![Postman runner][1]][1]

  1. Am I using the for loop correctly?
  2. What am I doing wrong?

EDIT
I forgot to add what my res returns when I send the URL:

[
  {
    "line1": "13579",
    "line2": "2468",
    "line3": "1234",
    "line4": "5678"
  },
  {
    "line1": "13468",
    "line2": "2425",
    "line3": "12578",
    "line4": "567343"
  },
  {
    "line1": "1test8",
    "line2": "24te25",
    "line3": "125st78",
    "line4": "567test343"
  }
]

Solution

  • My colleague helped me on this.

    The resolution is to use res[pm.info.iteration].line1.

    The full test would be:

        // start tests
        pm.test("expected line1 = " + (data["line1"]) + " | Actual line1 = " + (res[pm.info.iteration].line1), function () {
            pm.expect(res[pm.info.iteration].line1).to.equal(data["line1"]);
        });