Oct 5, 2020

API Testing 'A Beginners View': JavaScript push() Method

The push method adds values to the end of an array. The push method depends on the length property to determine where to start inserting the given elements. It changes the length of the array by the number of values added to the array. Syntax: arr.push(value1, value2 ....., valueN]]) Parameters: "valueN" - The value1(s) to add to the end of the array. Return value: This method returns the new length of the array after inserting the values into the array. Explanation with Example:
Response Body:












Test Script:
var resp = JSON.parse(responseBody);

//API Testing 'A Beginners View': JavaScript push() Method
accept_encoding = [];
var split = "gzip, deflate, br";
var split_value = split.split(",");
console.log("accept-encoding is: " + split_value);
accept_encoding.push(`${split_value[0]}`);
accept_encoding.push(`${split_value[1]}`);
accept_encoding.push(`${split_value[2]}`);
console.log(accept_encoding);
pm.environment.set("accept_encoding", (accept_encoding));

Console Output:





In the above example, I have used the previously published posts split() method and continued to add the push() method to store a list of values in an array.
The accept_encoding.push() method is used to push the split values into the "accept_encoding" array. Later I’m storing the array as an environment variable.

Environment Variable after the script looks as below:



No comments: