0
0
Postmantesting~15 mins

Setting variables in scripts in Postman - Build an Automation Script

Choose your learning style9 modes available
Set and use environment and global variables in Postman scripts
Preconditions (3)
Step 1: Open the Postman request
Step 2: Go to the Pre-request Script tab
Step 3: Set an environment variable named 'userId' with value '12345' using pm.environment.set()
Step 4: Set a global variable named 'authToken' with value 'abcdef' using pm.globals.set()
Step 5: Send the request
Step 6: Go to the Tests tab
Step 7: Write a script to retrieve 'userId' and 'authToken' variables using pm.environment.get() and pm.globals.get()
Step 8: Use pm.test() to assert that 'userId' equals '12345'
Step 9: Use pm.test() to assert that 'authToken' equals 'abcdef'
✅ Expected Result: The environment variable 'userId' and global variable 'authToken' are set before the request. After the request, the tests pass confirming the variables have the expected values.
Automation Requirements - Postman Sandbox scripting
Assertions Needed:
Assert environment variable 'userId' equals '12345'
Assert global variable 'authToken' equals 'abcdef'
Best Practices:
Use pm.environment.set() and pm.globals.set() to set variables
Use pm.environment.get() and pm.globals.get() to retrieve variables
Use pm.test() with descriptive messages for assertions
Keep scripts clear and simple for maintainability
Automated Solution
Postman
// Pre-request Script
pm.environment.set('userId', '12345');
pm.globals.set('authToken', 'abcdef');

// Tests Script
const userId = pm.environment.get('userId');
const authToken = pm.globals.get('authToken');

pm.test('Environment variable userId is set correctly', () => {
    pm.expect(userId).to.eql('12345');
});

pm.test('Global variable authToken is set correctly', () => {
    pm.expect(authToken).to.eql('abcdef');
});

In the Pre-request Script, we set the environment variable userId and the global variable authToken using pm.environment.set() and pm.globals.set(). This ensures these variables are available before the request runs.

In the Tests Script, we retrieve these variables using pm.environment.get() and pm.globals.get(). Then, we use pm.test() with clear messages to assert that the variables have the expected values. This confirms the variables were set correctly.

This approach keeps scripts simple and easy to understand, which is important for maintaining tests over time.

Common Mistakes - 3 Pitfalls
Using pm.variables.set() instead of pm.environment.set() or pm.globals.set() for setting environment or global variables
Trying to access variables before setting them
Not using pm.test() for assertions and instead using console.log() only
Bonus Challenge

Now add data-driven testing by setting 'userId' and 'authToken' with three different pairs of values in separate requests

Show Hint