Reputation: 442
I have variable "TOKEN" in my collection scope. I try to set the value using Tests scripts when do a request. But the variable not changed.
So, I try to use environment scope variable. And It works.
Why It's doesn't work when in collection scope? I had read about postman variable scope here and understand it well.
Here're some screenshots:
1. First, I call login endpoint.
Below is the console result. Nothing wrong.
Until I try to get all users endpoint that required token in request header. The status is 401 because the token is null. If the token is not null, then it will return 200:
It's gracefully working when I add "TOKEN" variable to environment. Switch to No Environment again will result 401 status code:
Upvotes: 6
Views: 6718
Reputation: 700
You can now use:
pm.collectionVariables.set("variable_key", "variable_value");
Upvotes: 1
Reputation: 46
This may be new since this question was posted, but for anyone else finding this, you can set collection variables using:
pm.collectionVariables.set(key, value)
See: https://learning.postman.com/docs/sending-requests/variables/#defining-variables-in-scripts
Upvotes: 3
Reputation: 159
It seems you can only set env variables when some environment is selected: https://learning.postman.com/docs/postman/scripts/postman-sandbox/#environment-and-global-variables
Upvotes: 0