Oct 8, 2020

API Testing 'A Beginners View': How to use JavaScript Arraylist in POSTMAN using counter? & How to reset the counter after run?

Q. 1 How to use JavaScript Arraylist in POSTMAN

Let assume that you have an array (or any collection) of items, each of which you need to pass into the request one by one. How do we do this? 


This was one of my major questions that were running through my mind these days after knowing how to store a list of response values as variables. On doing some R&D and checking with friends I got to know about the usage of counters and I was able to solve my problem. So today let’s check out how I tackled this.


You need to do the below things as a start in POSTMAN:





Now in the Request on «Pre-request Script» tab you need:
  • Get the array of items from the variable that you prepared to hold the array of records.
  • Get an index for current request from variable;
  • Set an item according to an index into another variable for the current request.
  • Increment index and save a new value after current request. It will be used for request a new item on the next iteration;
Example is below:

let value = pm.environment.get("countArr");

let item = pm.environment.get("itemOfArray");

pm.environment.set("ABC", value[item]);

pm.environment.set("itemOfArray", Number(item) + 1);


Now run your single request in Collection Runner. Before starting you need:

  • Set a number of iterations = quantity of your itemOfArray;
  • Iterations = array.length


Q.2 How to reset the counter after a run?

The next thing while working popped my mind was about the reset of the counter, why to manually reset it after every run, then on doing some googling work got an idea of creating a pre-request script in the previous request which pushes the response value to an array to reset the counter after the whatever static iterations we want the counter to be reset. In my case I wanted the counter to be reset after 10 iterations so used the Pre-Request script option and tried the below snippet:

//resetting back to 0 the counter

let count_array = pm.environment.get("itemOfArray");

console.log(count_array );

    if ((count_array  == 10)) 

    {

        pm.environment.set("itemOfArray","0");

        console.log(count_array);

    }


A simple way of resetting 😊 and it worked for me.


No comments: