Variable scope and precedence in Postman - Build an Automation Script
// Pre-request Script pm.globals.set('var1', 'globalValue'); pm.environment.set('var1', 'envValue'); pm.collectionVariables.set('var1', 'collectionValue'); pm.variables.set('var1', 'localValue'); // Request URL example: https://example.com/api?param={{var1}} // Tests Script const varValue = pm.variables.get('var1'); console.log('Value of var1:', varValue); pm.test('Variable scope precedence test', function () { pm.expect(varValue).to.eql('localValue'); });
First, we set the variable 'var1' in all scopes: global, environment, collection, and local (Pre-request Script).
Local variables set with pm.variables.set() have the highest precedence and override others.
In the request URL, {{var1}} will resolve to the local variable value 'localValue'.
In the Tests script, we retrieve the variable using pm.variables.get('var1'), which respects the scope precedence and returns 'localValue'.
The assertion checks that the retrieved value matches the expected local variable value, confirming the precedence order.
Logging to the Postman Console helps verify the actual value during test execution.
Now add data-driven testing by setting 'var1' to three different values in local scope and verify the precedence each time.