Postman test to check if every item of response's body has id existing in an array

Viewed 381

The task is to check if every item of response's body has id existing in an array. Let me show you an example:

let json = [
    { "name": "Ford", "id": "6" },
    { "name": "BMW", "id": "7" },
    { "name": "Abcd", "id": "8" },
    { "name": "Def", "id": "9" },
    { "name": "Ford", "id": "12" },
    { "name": "GHI", "id": "10" }
]

let ids = ["6", "7", "8", "9"]

I would like to check if every item form json has and id existing in ids. I tried using a loop like this one

 for (var i = 0; i < json.length; i++) {
        console.log(ids.includes(json[i].id))
    }

But i guess there must be more appropriate way. How would you write a test for this task?

2 Answers

Thanks mkamranhamid, I might have jumped the gun with this post. I've realised that it could be done like this:

pm.test("Every item has id from ids[]", function () {
    for (var i = 0; i < json.length; i++) {
        pm.expect(json[i].id).to.be.oneOf(ids)
    }
})

Using forEach instead of for:

pm.test("Every item has id an from ids[]", () => {
    response.forEach(element => pm.expect(element.id).to.be.oneOf(ids));
});

Or check if every element has an id to make it more "generic"

pm.test("Every item has an id", () => {
    response.forEach(element => pm.expect(element).to.has.deep.property('id'));
});
Related