Oct 7, 2020

API Testing 'A Beginners View': How to push list of values into a array and store as variable in POSTMAN using javascripting

In API testing sometimes we need to store a list of response values from one request, that needs to be used in another request without any usage of a data-driven approach. In such a situation, Javascript has an awesome method Array.push() Method. 

Recently at work, I had a situation to store a list of values wherein got to know about the Array.push() method, so thought of sharing with all who are new to API testing like me :-)


The JavaScript Array.push() method adds a new element to the end of the array. When doing so, the array’s length property increases by one. After adding the new element to the end of the array, this method returns the new length of the array.


Example # Used in my daily work


var resp = JSON.parse(responseBody); //parsing the JSON response

console.log(resp); //printing the response in console

countArr = []; //array that would store the list of values

for (var i=0; i<resp.length; i++) //this will loop in through the data in response

{

//pushing the attribute value from response to the array

countArr.push(`${resp[i].attributes.value}`);

console.log(countArr);

//storing the array as an environment variable for further use

pm.environment.set('countArr', (countArr));

}


In Example, our array starts out with zero elements. The first console.log(resp) allows you to print the parsed JSON response in the console. We then loop in through the response and use the Array object’s push() method to add elements to the array ‘countArr’. Notice that when we do this, we wrap the call in a console.log() call, allowing us to see that the push() method has returned the list of records as expected. Then, we have used the pm.environment.set("variable_key", "variable_value"); to store the array as an variable for further use in the next requests.

No comments: