Selecting 2nd object in an array in Postman

Viewed 465

AH, a very simple question, but I can't seem to find the answer anywhere. This is my first set of postman tests. I have a request that returns this JSON response:

{
    "requestId": "3dd0#170fa14fb64",
    "result": [
        {
            "id": 52508,
            "status": "deleted"
        },
        {
            "id": 52507,
            "status": "deleted"
        }
    ],
    "success": true

I want to write a test that verifies that both of the status objects within the result array will have the value "deleted" but I don't know the correct syntax to do so...so far I have this

pm.test("Test users deleted successfully", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.result[0].status).to.eql("deleted");
    });

This works great for verifying the first status object, but how do I target the second one in that array?

1 Answers

You would need to loop through the result array:

pm.test("Test users deleted successfully", () => {
    var jsonData = pm.response.json();
    _.each(jsonData.result, (item) => {
        pm.expect(item.status).to.eql("deleted"); 
    });
});

I've used the Lodash .each() function here, which is built-in to Postman, but you can do this with a native JS for loop, it works the same way I just prefer this syntax.

More info: https://www.w3schools.com/js/js_loop_for.asp

Related