Hey everyone
I am working on automating a few tests using Postman and ran into a bit of a roadblock. I need to set a dynamic variable in the Pre-request Script that generates a timestamp and passes it into the request body. I have tried using pm.environment.set()
with new Date().toISOString()
but it’s not always consistent across multiple requests in a collection run.
Here’s what I am doing:
let currentTime = new Date().toISOString();
pm.environment.set("timestamp", currentTime);
Then in the body:
{
"created_at": "{{timestamp}}"
}
Sometimes it works, sometimes it doesn’t. Has anyone else faced this: ?? Should I be using pm.variables.set()
instead of environment
: ?? I am also wondering if there’s a better approach when running tests in parallel or using the Collection Runner.
Appreciate any tips or best practices you have found when working with dynamic time values in Postman !! I have also gone through this topics Checking dynamic variables in pre-request script, salesforce course in mumbai but couldn’t understand anything.
Thanks in advance !!
Derek
Hi @derektehelr , You are right. You should use pm.variables.set()
instead of environment
because pm.variable.set has local scope where environemnt has global scope .
let currentTime = new Date().toISOString();
pm.variables.set(“timestamp”, currentTime);
console.log(“Generated timestamp:”, currentTime);
Thanks,
Jyoti
Store and reuse values using variables | Postman Docs
Environment variables should work just fine. An Environment variable is not a global variable.
The usual issue when Environment variables don’t work is that the Environment isn’t selected for the Collection Run.
Here are the variable scopes.
As a dynamic variable isn’t really confidential, I wouldn’t necessarily create it as an Environment variable.
A Local variable (set by pm.variables) is the lowest scope variable, so will override any other variable of the same name scoped elsewhere.
Local variables will only exist for that single request or a collection. They will not persist between Collection runs.
Therefore as long as you are not interested in the value of that variable, then this will be fine. If you want to keep the value for comparison, then you will need to save it to a Collection or Environment variable. Global would be overkill as it will mean that variable is available to all of your collections in that workspace.