I want to set the real value of $randomFirstName on the environmental level so I can access the test script. I am able to see the value generated by $randomFirstName in response body but the same value I’m unable to set as an environmental variable. please guide me!
I managed to do it by saving the name to a different Environment Variable.
Shows in Environment Variables as:
There’s probably a better way of doing this, I think I’d opt for it to be logged in the console if it were me, as I could have the logs documented in Jenkins.
Step 1. Pre-request Script gets Executed
Step 2. Request is sent
Step 3. Response is received
Step 4. Test script is executed
Random variables are assigned during the phase when the request is being sent, now you can see that you won’t be able to access a random variable even before it has been assigned to something in a request. (Since you’re trying to access it in the pre-request script)
The curly braces syntax for variables (for eg: {{name}}) is only for the parts that belong to a request and not for pre-request or test scripts. To access variables in the scripts, you need to use the variable API’s which are for eg: pm.environment.get('variableName');
Now, to get around your problem of getting what random name was generated during the phase when the request was sent, you need to make use of the Test Script, which is executed after the response has been received.
In this test script, you need to take out the name from the request that was sent / response that was received.
You can access the request using pm.request and the response using pm.response.
For eg:
You want to find out the randomFirstName that was sent as part of a query param of the request.
Then you can write the following:
let randomName = pm.request.url.query.get('name');
pm.environment.set('randomName', randomName);
As you can see in the image below, I was able to log the random name that was sent in the request in the console:
Hey Liam, thank you for your guidance!
you can see in environmental variable, employeeName value is showing as {{$randomFirstName}}. what I want is the actual value in env variable which is passed in body. so that I can assert test on name attribute.