Run the same test through all arrays objects

Hey!

Is there a way to run the same test script through all array objects?

I have that pm.test that i want to run through all array objects, that in that case is 82, but it might be more or it might be less.

Is there a way to this?
Thanks a bunch!

pm.response.json() will most likely produce a JavaScript object, not an array.

Itโ€™s an important distinction as an ForEach loop only works with arrays.

Therefore, you need to wrap a for loop around your test.

In the following example(s). I have created an array, and Iโ€™ve included examples of both loops. I suspect you will need to use the first example.

var array = 
    [{
    "id": 377,
    "forename": "Forename 493068",
    },
    {
    "id": 376,
    "forename": "Forename 493067",
    },
    {
    "id": 375,
    "forename": "Forename 123456",
}];

console.log(typeof(array)); // array is a special type of "object"

pm.test("Array", () => {
    pm.expect(array).to.be.an("array"); // change this to object and it will fail
});

for (let i = 0; i < array.length; i++) {

    var id = array[i].id;
    // console.log(id);
    
    pm.test(`for loop expect ${id} to be an number`, () => {
        pm.expect(id).to.be.an("number");
    });

};

array.forEach(line => {

    var id = line.id;
     
    pm.test(`forEach loop expect ${id} to be an number`, () => {
        pm.expect(id).to.be.an("number");
    });
    
});

image

I donโ€™t quite understand why you are setting and retrieving a global variable within the same bit of code.

Appears superfluous unless you are using that variable in another request which considering you want to look through 80+ elements seems unlikely.

Why canโ€™t you just define the variable direct from the response.

Also, does it really need to be a global variable available to all collections.

I suspect if needed at all, it should be set as a collection or environment variable.