Test Overview
This test checks if a variable is correctly set in a Postman script and then used in a subsequent request. It verifies that the variable value is stored and accessible.
Jump into concepts and practice - no test required
This test checks if a variable is correctly set in a Postman script and then used in a subsequent request. It verifies that the variable value is stored and accessible.
pm.test("Set and use environment variable", function () { pm.environment.set("userId", "12345"); let userId = pm.environment.get("userId"); pm.expect(userId).to.eql("12345"); });
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | Postman test runner is ready to execute the script | — | PASS |
| 2 | Set environment variable 'userId' to '12345' using pm.environment.set | Environment variables now include userId = '12345' | — | PASS |
| 3 | Retrieve environment variable 'userId' using pm.environment.get | Variable userId retrieved with value '12345' | — | PASS |
| 4 | Assert that retrieved userId equals '12345' using pm.expect | Assertion compares expected '12345' with actual '12345' | pm.expect(userId).to.eql('12345') | PASS |
| 5 | Test ends successfully | Variable set and verified correctly | — | PASS |
pm.variables.set in Postman scripts?pm.variables.setpm.variables.set.token with value abc123 in a Postman test script?pm.variables.set('variableName', 'value'); with the variable name as a string and value as the second argument.pm.variables.set('userId', 42);
const id = pm.variables.get('userId');
console.log(id);pm.variables.get.console.log(id); prints 42 without quotes.pm.variables.set('session', 'abc');
pm.variables.get('session');session is not accessible in later requests. What is the likely problem?pm.variables.set sets a local variable only for the current script execution, not across requests.pm.environment.set instead.pm.environment.set to make it accessible across requests -> Option BauthToken in a Pre-request Script that depends on the response of a previous request stored in pm.response.json(). Which approach correctly sets authToken for use in the next request?pm.response.json() is only available in the Tests script after the request completes, not in the Pre-request Script.authToken in the next request, set it as an environment variable in the Tests script of the current request using pm.environment.set.pm.variables.set do not persist across requests, so they won't be available in the next request.