0
0
Postmantesting~15 mins

Conditional request execution (setNextRequest) in Postman - Build an Automation Script

Choose your learning style9 modes available
Conditional execution of Postman requests using setNextRequest
Preconditions (2)
Step 1: Send the 'Login' request with valid credentials.
Step 2: Check the 'success' field in the response JSON.
Step 3: If 'success' is true, execute the 'Get User Data' request next.
Step 4: If 'success' is false, do not execute any further requests.
✅ Expected Result: If login is successful, 'Get User Data' request runs next. If login fails, no further requests run.
Automation Requirements - Postman Sandbox JavaScript
Assertions Needed:
Verify 'success' field is present and boolean in 'Login' response.
Verify 'Get User Data' request runs only if 'success' is true.
Verify no further requests run if 'success' is false.
Best Practices:
Use pm.response.json() to parse JSON response safely.
Use pm.setNextRequest() to control request flow conditionally.
Avoid hardcoding request names; use exact request names as in collection.
Add clear console logs for debugging flow.
Automated Solution
Postman
pm.test('Check login success field exists and is boolean', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('success');
    pm.expect(jsonData.success).to.be.a('boolean');
});

const jsonData = pm.response.json();

if (jsonData.success === true) {
    console.log('Login successful, proceeding to Get User Data request');
    pm.setNextRequest('Get User Data');
} else {
    console.log('Login failed, stopping further requests');
    pm.setNextRequest(null);
}

This script runs in the Tests tab of the 'Login' request in Postman.

First, it checks that the response JSON has a success field and that it is a boolean. This ensures the response is as expected.

Then, it reads the success value. If true, it uses pm.setNextRequest('Get User Data') to tell Postman to run the 'Get User Data' request next.

If success is false, it calls pm.setNextRequest(null) to stop running any further requests.

Console logs help track the flow when running the collection.

Common Mistakes - 4 Pitfalls
Using incorrect request name in pm.setNextRequest
Not parsing response JSON before accessing fields
{'mistake': "Not handling the case when 'success' field is missing", 'why_bad': 'If the field is missing, the script may throw an error or behave unpredictably.', 'correct_approach': 'Add assertions to check the presence and type of the field before using it.'}
Not calling pm.setNextRequest(null) to stop requests on failure
Bonus Challenge

Now add data-driven testing with 3 different login credentials to test success and failure scenarios.

Show Hint