Conditional execution of Postman requests using setNextRequest
Preconditions (2)
✅ Expected Result: If login is successful, 'Get User Data' request runs next. If login fails, no further requests run.
Jump into concepts and practice - no test required
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.
Now add data-driven testing with 3 different login credentials to test success and failure scenarios.
pm.setNextRequest() in Postman?pm.setNextRequest()if (pm.response.code === 200) {
pm.setNextRequest('ProcessData');
} else {
pm.setNextRequest('ErrorHandler');
}
If the response code is 404, which request runs next?if (pm.response.code = 200) {
pm.setNextRequest('NextStep');
} else {
pm.setNextRequest('Stop');
}
What is the problem with this script?userExists is true, the next request is "GetUserData", else the flow stops. Which script correctly implements this in the test tab?