2

newbie at JavaScript and Postman here.

I have set up a basic test in postman using JS to compare names in a web response to names in a data file. The array of names is in an external data csv file.

I want to loop through the array, but I get an error:

"ReferenceError | i is not defined"

Code:

var newResponse = responseBody;

let nameArray = data.name;

for (let i = 0; i < nameArray.length; i++) {
  console.log(nameArray.length);
}

pm.test("Web vs. Data: Person", function() {
  pm.expect(newResponse.Item[i].name).to.equal(nameArray.Item[i].person);
});

console.log(newResponse.Item[i].name);
console.log(nameArray.Item[i].person);
MTCoster
  • 5,868
  • 3
  • 28
  • 49
  • Could you not use `pm.iterationData.get('name')` to get the value from the data file, I don't really understand why your looping through that in the why you are? – Danny Dainton Nov 17 '18 at 17:51

2 Answers2

1

Your end scope "}" character missing please change with this code;

var newResponse = responseBody;

let nameArray = data.name;

for (let i = 0; i < nameArray.length; i++) {

    console.log(nameArray.length);

    pm.test("Web vs. Data: Person", function () {
        pm.expect(newResponse.Item[i].name).to.equal(nameArray.Item[i].person);

    });

    console.log(newResponse.Item[i].name);
    console.log(nameArray.Item[i].person);
}
muratoner
  • 2,316
  • 3
  • 20
  • 32
0

let is block scoped so it will cause ReferenceError out of the for loop. The variable i will not be referred outside of the for loop. So you've to move your codeblock inside the for loop like below. Hope this helps :)

var newResponse = responseBody;
let nameArray = data.name;

for(let i = 0; i < nameArray.length; i++){
  console.log(nameArray.length);
  pm.test("Web vs. Data: Person" ,function(){
  pm.expect(newResponse.Item[i].name).to.equal(nameArray.Item[i].person);
  });

  console.log (newResponse.Item[i].name);
  console.log(nameArray.Item[i].person); 
}
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • 1
    I tried this, but I now get an error 'don't make functions within a loop'. Thanks for your quick help. – Bill_Martin Nov 17 '18 at 15:01
  • @Bill_Martin take a look here https://stackoverflow.com/questions/10320343/dont-make-functions-within-a-loop this will help you, need to move function outside of the loop and call it from the loop with incremented value of `i` – A l w a y s S u n n y Nov 17 '18 at 15:06