Search code examples
automated-testspostmanpostman-collection-runnerpostman-pre-request-script

Set env variables in multiple loops using postman


I want to test the following workflow structure.

in first request script,

var st = [1,2,3]
var i = st.length;
for(var j=0; j<i; j++) {
    pm.environment.set("id", st[j]);
    postman.setNextRequest("getNext");
};

In getNext pre test script,

var id = pm.environment.get("id");
console.log(`Run ${id}`);

In console, there is only Run 3 message is shown.

The problem is that the env variables are overwritten with the last elements. And I can see only the last element of the list and the requests are using the last element.

I would like to know How can I keep the env variables not to be overwritten?

EDIT I remove my messy question and add simple workflow.


Solution

  • postman.setNextRequest() is always executed at the end of the current request. This means that if you put this function before other code blocks anywhere in pre-request or test script, these blocks will still execute.

    That means, the loop runs 3x, and only at the very end, when the complete script is finished, it calls the postman.setNextRequest(), when id has the value 3.

    See documentation for more details.

    Found this blog post, that's explaining how you can achieve it: https://ambertests.com/2019/01/28/postman-how-to-dynamic-iteration-within-a-collection/