I have searched for the solution and found multiple answers but didn’t work for me.
Under Collection Folder/Parent folder → Under Pre-request script ..
[Note - env_amount is created under Collection Folder → Variables tab]
function getAmount()
{ const amount= (“random_number”, _.random(1, 10));
pm.environment.set(“env_amount”,amount);
};
In the later folders/ tests - need to get this amount in ‘Body’ request. So I have added the following stmt to Pre-request of that test:
var amount=pm.collectionVariables.get(“getAmount”)();
In the body of the test -
“amount”: {{amount}},
its not working.
Your function is trying to set an environment variable, where in the pre-request script you have it trying to retrieve a collection variable that doesn’t appear to be declared anywhere.
The best way to declare a function is to define it as a global variable (don’t use LET, VAR or CONST)
utils = {
getAmount: function (pm) {
const amount = ("random_number", _.random(1, 10));
pm.environment.set("env_amount", amount);
return 'hello';
},
response: function (pm) {
console.log(pm.response.json());
return 'hello';
}
};
If you need access to Postman functions like pm.response or pm.environment, then you have to pass pm as an argument to the function.
Calling the function is then straight forward.
utils.getAmount(pm); //or
utils.response(pm);
All you should need for your body is the following.
{
"amount": {{env_amount}}
}
This will use the environment variable you set in the function.