Iterative Post request in Postman

Viewed 186

I need help for doing Post request repeatedly in Postman with different bodies. Example given below, where company name must be changed. It would be better to read company names from a document or may be from an array in script. Please advice how can I do it?

{
  "d": "{{company}}"
}

I found somethin like that, but I am getting error: (There was an error in evaluating the Pre-request Script: TypeError: Cannot read property 'get' of undefined)

Pre-request Script:

if(!companies){
    companies = ["111",
                 "222",
                 "333"];
}

var currentCompany = companies.shift();
pm.enviroment.set("company",currentCompany);
pm.enviroment.set("companies", companies);

Tests:

var companies = pm.enviroment.get("companies");


if(companies && companies.length > 0){
    postman.setNextRequest("my url");
} else {
    postman.setNextRequest(null);
}
1 Answers

There are multiple but small mistakes:

  1. the set environment function is misspelled: please use pm.environment.set(right) instead of pm.enviroment.set(false)
  2. you have to load the companies var from the environments before. Add var companies = JSON.parse(pm.environment.get("companies")); to the first line of your pre rquest script.
  3. Please make sure that you are saving string values to the environment vars. Use JSON.stringify(myObject) e.g. pm.environment.set("company", JSON.stringify(currentCompany)); and analogue JSON.parse(myStringVar) for loading variables in var companies = JSON.parse(pm.enviroment.get("companies"));
  4. (Maye also a problem) Please make sure, there is a enviroment chosen in Postman, postman-runner and newman. If there is no environment set, you can get errors: enter image description here
Related