How to specify how many times to run a request?

I need to run a request x many times. Instead of creating that as x separate requests is there a way I can utilize the pre-request or test scripts to do this?

I was thinking of setting a counter to 0, and setNextRequest to the current one, increment counter and do this until you reach your count, however, doing this will bring you into an infinite loop because it will keep setting counter to 0.

Thank you.

I recommend using the array.shift() and array.length() method to control your loop.

If you use a straight up IF condition checking if the counter is more than or equals X, it will always run one more time than you expect because setNextRequest() just sets the next request that will run after the current request.

shift() is a method available to arrays that retrieves the first element from an array, and then deletes it from the array.

Iā€™m using the from() and key() methods to generate the array with x numbers.

javascript - How to create an array containing 1ā€¦N - Stack Overflow

The following is a basic example using Postman Echo.

image

x = 5;

if (typeof array === 'undefined' || array.length == 0) {
    array = Array.from({length: x}, (_, i) => i + 1)
    pm.collectionVariables.clear("currentCount");
}


let counter = array.shift();
pm.collectionVariables.set("currentCount", counter);

if (array.length > 0) {  
    currentRequest = pm.info.requestName;
    postman.setNextRequest(currentRequest);
} 

Which you can see from the console logs run 5 times as expected.

image

1 Like

Thank you - Works great!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.