setNextRequest() doesn't work

Hi @oasis,

If I understand your use-case correctly, the solution you have implemented would not work.

postman.setNextRequest() is not a “call” to the request it just sets which request will be executed, once the “current request” + “test-script” finish executing.

If postman.setNextRequest is called multiple times in a script, the last request set by postman.setNexRequest() will be executed.

In your initializer request, you have a for() loop iterating over request names and based on the current item you are setting the next-request to execute. Since the last request set by the for-loop is null, which means do not execute any other request, only your initializer request runs.

Read-up the documentation for more details: https://learning.postman.com/docs/running-collections/building-workflows/


Potential solution

On a high-level, you would want to store your array and an index in an environment variable.

For example in your initializer request’s Pre-request script do this

var requests = [ 
    "Stop",
    "WC invalid request with pickup date>90 days",
    "WC valid request without 'serviceCode'",
    "WC valid request with pickup date  on day 90"
];

pm.collectionVariables.set('requests', JSON.stringify(requests));

You can see I’ve removed “WC valid request with all default values” from the array, since this request will get executed automatically after the initializer-request completes. And I have reversed the order - since we will be using it as a stack.

Now - in your last request Get booked status - in the test script - at the very end - put the following.

var requests = JSON.parse(pm.collectionVariables.get(`requests`)); // Retrieve the collection variable's value
var nextRequest = request.pop(); // This will be next request's name we want to execute

// Update the collection variable's value
pm.collectionVariables.set('requests', JSON.stringify(requests));

if(nextRequest === 'Stop') { 
    postman.setNextRequest(null);
} else {
   postman.setNextRequest(nextRequest);
}

What this will do is, that if the popped item is ‘Stop’, Postman will stop execution - if not, it will use that value to set the next request to run.

2 Likes