Run Postman pre-request script before every request in a runner

I have a simple Postman pre-request script:

vehicles = ['car', 'van', 'truck']
pm.globals.set('vehicle', vehicles[Math.floor(Math.random() * vehicles.length)]);

It is then used in the json body of the request to the api, randomly sending a vehicle type to the API.

However when I try to run this request multiple times e.g. 100 through Runner, the random value is selected for the first request and then continually used for the remaining 99.

How do I get this pre-request script to be run for every request in the runner?


So, with out seeing what else you are doing, eg is this a pre-request script in the collection, the folder, or the method? It would be hard to tell. That said, globals aren’t where you would want to put that value, it should at minimum go into the collection variables


Here is the link to the page you can read up on them from the postman site:
Postman Variables
You are using Globals … but better yet, since it doesn’t look like you need it again … I would suggest putting it in the environment or the local variables area’s.

What goes in what?

In general, don’t use globals … they make it super hard to debug your stuff after it starts to grow.
I almost always can figure out how to put everything in either: collection or environment. The trick with local variables is that they take precedence over every other type … so use them with care. If you ask for one with: pm.variables.get('something') … it will give you the narrowest scope it can. So if you defined a local with the name of something then it will take that one even if you have global, collection, or environment one with the same name … that is the order of precedence too :slight_smile:

A possible answer

So I would say to try either of these:

// just doing this to make the code easier to test in the script I made
// I don’t like to put code in line cause it makes it harder to for me to read later :slight_smile:

const vehicles = [ ‘car’, ‘van’, ‘truck’]
const itemToSend = vehicles[Math.floor(Math.random() * vehicles.length)]

Then you can do either:

pm.environment.set('vehicle', itemToSend)



That way you can do this in your post for your json:
{ "vehicle": "{{itemToSend}}" }

Hope that all makes sense.