But the variable is not set after the request. What is the most likely reason?
medium
A. The header name is case-sensitive and should be 'session-id'
B. You must parse the response body before setting variables
C. pm.globals.set cannot set variables from headers
D. pm.response.headers.get() returns null if header is missing or name is wrong
Solution
Step 1: Understand header retrieval in Postman
Header names are case-insensitive, but if the header is missing or name is wrong, get() returns null.
Step 2: Check why variable is not set
If pm.response.headers.get('Session-ID') returns null, the variable is set to null or empty, appearing unset.
Final Answer:
pm.response.headers.get() returns null if header is missing or name is wrong -> Option D
Quick Check:
Header get returns null if missing [OK]
Hint: Check header name and existence before setting variable [OK]
Common Mistakes:
Assuming header names are case-sensitive
Believing pm.globals.set can't set from headers
Forgetting to check if header exists
5. You want to set a collection variable authToken from a nested JSON response where the token may sometimes be missing. Which script correctly sets authToken to the token value if present, or to an empty string if missing?
hard
A. const token = pm.response.json()?.auth?.token ?? ''; pm.collectionVariables.set('authToken', token);
B. pm.collectionVariables.set('authToken', pm.response.json().auth.token);
C. if(pm.response.json().auth.token) { pm.collectionVariables.set('authToken', pm.response.json().auth.token); }
D. pm.collectionVariables.set('authToken', pm.response.json().auth?.token || null);
Solution
Step 1: Handle optional chaining to avoid errors if token missing
Using ?. safely accesses nested properties without error if missing.
Step 2: Use nullish coalescing ?? to set empty string if token is undefined or null
This ensures authToken is never undefined, avoiding test failures.
Step 3: Set collection variable with the safe token value
pm.collectionVariables.set('authToken', token); stores the value correctly.