When working with Postman to automate API testing, you might encounter scenarios where you want to conditionally skip the execution of subsequent requests in a collection. This can be useful if a certain condition isn't met in your API responses. Here's a guide on how to achieve this using Postman's scripting capabilities.
Scenario
Imagine you have a collection where the first request returns a response like this:
{
"content": "True",
"statusCode": 200,
"message": "Global value got from DbConfig!"
}
You want to skip all subsequent requests if the content
field is "False"
.
Step-by-Step Guide
-
Set Up Your Collection: Ensure your collection is organized with the request you want to evaluate placed at the beginning.
-
Write a Post-Request Script: In the test script section of the first request, you'll write a script to check the content
field and decide whether to continue the collection run.
// Parse the response
let response = pm.response.json();
// Check the content value
if (response.content === "False") {
pm.execution.setNextRequest(null); // Skip the remaining requests
}
This script checks if the content
is "False"
. If it is, pm.setNextRequest(null)
stops all subsequent requests from running.
-
Test the Flow: Run your collection to see the logic in action. If the condition is met (i.e., content
is "False"
), the collection run will halt after the first request.
Explanation
pm.response.json()
: This method parses the JSON response from your request.
pm.setNextRequest(null)
: This function is used to stop further requests in the collection run. If the condition isn't met, the collection continues with all remaining requests in their original order.
Benefits
- Efficiency: Avoid unnecessary API calls when certain conditions aren’t met, saving time and resources.
- Control: Gain greater control over your testing workflows by dynamically determining execution paths.
Conclusion
Using pm.execution.setNextRequest(null)
in a test script provides a straightforward way to control the flow of your Postman collection runs based on specific conditions in your API responses. This technique can be a powerful tool in optimizing your automated testing processes.
Feel free to customize the logic to fit your specific needs!
I tried a few ways to write a script that can be reused among a few of postman request collections and finally I got a solution I like.
- Using
const
or let
keywords to define internal used objects or utility containers. For example
const stpCommon = {
randomCharacters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'.split(''),
nonUsdCurrencies: 'GBP,AUD,NZD,CAD,JPY,EUR'.split(','),
getCurrencyPair: (currency) => `${currency}/USD`,
getRandomRate: () => (Math.random() * 0.9 + 0.8).toFixed(5),
getRandomElement: (array) => {
if (array.length === 0) {
throw new Error('Cannot get a random element from an empty array');
}
const randomIndex = Math.floor(Math.random() * array.length);
return array[randomIndex];
},
getNextWeekday: function (date) {
const clonedDate = new Date(date);
const day = clonedDate.getDay();
if (day === 6) {
clonedDate.setDate(clonedDate.getDate() + 2);
} else if (day === 0) {
clonedDate.setDate(clonedDate.getDate() + 1);
}
},
getBasicRequest: () => {
const fixedAmountCurrency = stpCommon.getFixedAmountCurrency()
return {
currencyPair: stpCommon.getCurrencyPair(fixedAmountCurrency),
rate: stpCommon.getRandomRate(),
side: "2",
fixedAmount: stpCommon.getFixedAmount(),
...
}
...
- Using object name itself in its member methods. don't use
this
keyword, see the last method in above example.
- At the end of your script, using a conditional block to expose the object you want in Postman environment, normally one object is enough. For instance:
// the only way to expose an object in postman, is to define a object without any declaration keywords like var/let/const
// the following is a hack to expose the object in postman without troubling Node.js as in Node.js, we are not allowed to
// define a variable without any declaration keywords like var/let/const
if (typeof(pm) !== 'undefined') {
stpUtils = _stpUtils
}
- At the end of your script, utilize conditional exports the objects that you want to use in Node.js environment, this step enables writing test cases for it. For example
const utilsA = {...}
const utilsB = {...}
const _utilsC = {something using utilsA & utilsB}
// provided you want to use utilsC in postman
if (typeof(pm) !== 'undefined') {
utilsC = _utilsC
}
// and you want to expose all objects in your test cases
if (typeof (module) !== 'undefined') {
module.exports = {
utilsA, utilsB, _utilsC
}
}
This way, you can paste all the script body into the postman scripts tab without trouble, while in Node.js env, you can freely use Jest or other unit test framework to write test cases for your shard library. What a great solution!