If/Else Statement on Pre-Request script

Hello Everyone,
im trying to run a collection that has several requests inside it. I will explain more or less how it works:
Get request → just get a index
Post Request → Create a file on a data base
Patch Request → Update the status of the file

My problem is on the patch request, it runs every time. This “IF” is not working at all.
Im using this:

if(pm.collectionVariables.get("status") !== "draft"){
postman.setNextRequest();

}

So im trying to check the status of the file before running the request, if the status is different, i will go for the next request, and so on.

Can anyone give me some light on this issue?

Hi @aerospace-candidate1 ,

There are a couple of things to bear in mind from the Building request workflows help (scroll to the “Stop workflow execution” section).

Firstly, you need to specify null for the value of the next request - i.e. postman.setNextRequest(null);

Secondly, you need to bear in mind this note:

  • 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.

So if you have other code after this if statement, it will still be executed regardless of status - you might want to put the remaining code into an else block if you don’t want it to run further.

Okay, i kind of understand. So how can i run a collection and make a statement to check before running a specific request like this:?
1- Run
2- Check if it is to run or not, dont run
3- run
4- …

It’s difficult to give a definite answer without seeing a screenshot of your requests, or a bit more context of your scripts, but if you have three requests:

Get Request
Post Request
Patch Request

…and you want to skip Patch Request according to status, then you could insert the following script at the bottom of the Tests tab for Post Request:

if(pm.collectionVariables.get("status") !== "draft"){
 postman.setNextRequest(null);
}

If you have a fourth request, and you just want to skip Patch Request and move onto the next request in the collection, you can specify the request name instead:

if(pm.collectionVariables.get("status") !== "draft"){
 postman.setNextRequest("Name of next request");
}

If this is creating confusion then please share as much information as you are able :slight_smile:

1 Like

Add a setup request where you will check which request to send next and use postman.setNextRequest

Postman.setNextRequest won’t skip the current request , it will get triggered only after the request in which it is defined has completed execution

1 Like

I was thinking so much of Pre-Request that i forgot that i could put in the last part of test and call the request i wanted!

Thanks guys!