0
0
Postmantesting~15 mins

Why pre-request scripts prepare data in Postman - Automation Benefits in Action

Choose your learning style9 modes available
Verify pre-request script prepares data correctly before API call
Preconditions (3)
Step 1: Open the Postman collection and select the API request
Step 2: Go to the Pre-request Script tab
Step 3: Write a script that generates a token and saves it to an environment variable 'authToken'
Step 4: Go to the Headers tab and add 'Authorization' header with value 'Bearer {{authToken}}'
Step 5: Send the API request
Step 6: Observe the request headers and response
✅ Expected Result: The API request includes the Authorization header with the token generated by the pre-request script, and the API responds successfully using the prepared data
Automation Requirements - Postman test scripts
Assertions Needed:
Verify environment variable 'authToken' is set before the request
Verify the Authorization header contains the correct token
Verify the API response status code is 200
Best Practices:
Use pm.environment.set() to store data in pre-request scripts
Use pm.request.headers to verify headers
Use pm.test() for assertions
Keep scripts simple and focused on preparing data
Automated Solution
Postman
pm.test('Pre-request script sets authToken', function () {
    pm.expect(pm.environment.get('authToken')).to.be.a('string').and.not.empty;
});

pm.test('Authorization header contains authToken', function () {
    const authHeader = pm.request.headers.get('Authorization');
    const token = pm.environment.get('authToken');
    pm.expect(authHeader).to.equal(`Bearer ${token}`);
});

pm.test('Response status is 200', function () {
    pm.response.to.have.status(200);
});

The first test checks that the pre-request script has set the environment variable authToken to a non-empty string before the request is sent.

The second test verifies that the Authorization header in the request includes the token prepared by the pre-request script, ensuring the API receives the correct data.

The third test confirms the API responded with status code 200, indicating success.

Using pm.environment.set() in the pre-request script stores data for use in the request. The tests use pm.test() and pm.expect() for clear, readable assertions.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not setting environment variable in pre-request script', 'why_bad': "The token or data won't be available for the request, causing failures.", 'correct_approach': 'Always use pm.environment.set() or pm.variables.set() to store data before the request.'}
Hardcoding token value instead of generating dynamically
Not verifying that the header uses the prepared token
Bonus Challenge

Now add data-driven testing by preparing different tokens for three different user roles and verify the API response for each.

Show Hint