title: Reusing test loops in Postman
body: <p>I am have the following loop which triggers a the same Get Request until an order is processed and the correct status is set.</p>
  <p>The problem is that I have to use the same snippet on different scenarios and each time there is a change i have to change the snippet in multiple places.</p>
  <p>What I would like to do is to set the snippet at collection level and then call it in the requests Tests area.</p>
  <p><strong>Expected behavior:</strong>
  The loop checks the response body and if a certain status is not set then it retriggers the same request until the status is set after that it retriggers the request again and then moves on to the next request.</p>
  <p>There is also a counter implemented to avoid infinite loops in case something happens.</p>
  <p>My question is how can this be set as a method at collection level. For other functions I used <a href="https://stackoverflow.com/questions/45673961/how-to-write-global-functions-in-postman">THIS</a> approach and it worked but for some unknown reason for this function it does not work it either goes into a wrong branch or does not loop the same request when called.</p>
  <p>Code snippet used:</p>
  <pre><code>var jsonData = pm.response.json()[0];
  var READY_STATUS = jsonData.deliveryGroups[0].history.find(elem =&gt; elem.status === &quot;Preparing_Status&quot;);
  pm.environment.get(&quot;retryCounter&quot;)===undefined ? pm.environment.set('retryCounter',10):null
  retryCount = pm.environment.get(&quot;retryCounter&quot;);
  if (!READY_STATUS &amp;&amp; retryCount &gt; 0){
      retryCount = retryCount - 1;
      pm.environment.set('retryCounter',retryCount);
      console.log(retryCount);
      pm.test(&quot;Delivery group not in ready status&quot;, function(){});
      postman.setNextRequest(pm.info.requestId);
      setTimeout(() =&gt; {}, 5000);
  } else if (jsonData.deliveryGroups[0].status === &quot;READY_STATUS&quot; &amp;&amp; retryCount &gt; 0) {
      retryCount = retryCount - 1;
      console.log(retryCount);
      pm.environment.set('retryCounter',retryCount);
      pm.test(&quot;Delivery group and items in READY_STATUS_Status state&quot;, function () {
      pm.expect(jsonData.deliveryGroups[0].status).to.eql(&quot;READY_STATUS&quot;);
      pm.expect(jsonData.deliveryGroups[0].items[0].status).to.eql(&quot;READY_STATUS&quot;);
      pm.expect(jsonData.deliveryGroups[0].items[1].status).to.eql(&quot;READY_STATUS&quot;);
      pm.expect(jsonData.deliveryGroups[0].items[2].status).to.eql(&quot;READY_STATUS&quot;);
      });
      postman.setNextRequest(pm.info.requestId);
      setTimeout(() =&gt; {}, 10000);
  } else if(retryCount === 0){
      pm.test(&quot;Test failed&quot;, function(){
          throw Error(&quot;Test failed&quot;)
      });
      postman.setNextRequest(null);
  }
  else {
      pm.test(&quot;Moving on to next test&quot;, function(){});
      postman.setNextRequest();
  }
  </code></pre>