0
0
Postmantesting~15 mins

Script execution order in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify Postman script execution order
Preconditions (2)
Step 1: Open the Postman collection
Step 2: Add a Pre-request Script at the collection level that sets a variable 'order' to 'collection'
Step 3: Add a Pre-request Script at the folder level that appends '-folder' to the 'order' variable
Step 4: Add a Pre-request Script at the request level that appends '-request' to the 'order' variable
Step 5: Send the request
Step 6: Add a Test script at the request level that reads the 'order' variable and saves it to the test result
Step 7: Run the request and observe the test result
✅ Expected Result: The 'order' variable value in the test result should be 'collection-folder-request', showing the scripts ran in the correct order
Automation Requirements - Postman Sandbox JavaScript
Assertions Needed:
Verify the 'order' variable equals 'collection-folder-request' after request execution
Best Practices:
Use pm.variables.set and pm.variables.get to manage variables
Use console.log for debugging script execution order
Keep scripts simple and focused on their scope level
Automated Solution
Postman
// Collection Pre-request Script
pm.variables.set('order', 'collection');

// Folder Pre-request Script
let currentOrder = pm.variables.get('order');
pm.variables.set('order', currentOrder + '-folder');

// Request Pre-request Script
let orderSoFar = pm.variables.get('order');
pm.variables.set('order', orderSoFar + '-request');

// Request Test Script
let finalOrder = pm.variables.get('order');
pm.test('Script execution order is correct', function () {
    pm.expect(finalOrder).to.eql('collection-folder-request');
});

The collection pre-request script sets the initial variable 'order' to 'collection'.

The folder pre-request script appends '-folder' to the existing 'order' variable.

The request pre-request script appends '-request' to the 'order' variable.

Finally, the test script verifies that the 'order' variable equals 'collection-folder-request', confirming the scripts executed in the correct order.

This approach uses Postman Sandbox's pm.variables API to share variables across script scopes during the request lifecycle.

Common Mistakes - 3 Pitfalls
Using pm.environment or pm.collectionVariables instead of pm.variables for temporary request lifecycle variables
Not appending strings properly, causing the order variable to overwrite instead of accumulate
Placing all scripts only at the request level
Bonus Challenge

Now add a Post-request Script at the collection level that appends '-post' to the 'order' variable and verify the final value includes this suffix.

Show Hint