Test to find a keyword in a response array

Hi, good day everyone, i am new here,

My question:
I have a response data looking like this

[
    {
        "Outlet": "Outlet1",
        "Inventory": 12
    },
    {
        "Outlet": "Outlet2",
        "Inventory": 0
    },
    {
        "Outlet": "Outlet3",
        "Inventory": 3
    },
    {
        "Outlet": "Outlet4",
        "Inventory": 0
    }
}

How I found the problem:

I need to verify if the outlet 1 inventory is exact 12, and every other data EXCEPT outlet1 inventory is 0. do i need to loop the test?

I’ve already tried:

pm.test("Inventory.OnHand Outlet1 == 6", () => {
    let Outlet1Result = jsonData.find(a => a.Outlet === "Outlet1")
    pm.expect(Outlet1Result.Outlet).to.eql("Outlet1")
    pm.expect(Outlet1Result.Inventory).to.eql(12)
});


pm.test("Inventory.OnHand not Outlet1 == 0", () => {
    if (jsonData.Outlet !== "Outlet1") {
    jsonData.forEach(function() {
        let result2 = jsonData.find(a => a.Outlet !== "Outlet1")
        pm.expect(result2.Inventory).to.eql(0)
    }) ;
  }  
});

I have tried using this 2 test, the first test worked just fine, but i think the second test is wrong because it’s passed, it should not be passed since outlet 3 inventory is 3, the text expect it to be 0

Hey @freakend ! Welcome to the community :partying_face:

You can save the response and loop through the objects to find and perform the tests you need, Have a look at how this can simplified.

var jsonData=pm.response.json();

pm.test('Inventoy Check', () => {
    _.each(jsonData, (item) => {
       
        if(item.Outlet=="Outlet1")
        pm.expect(item.Inventory).to.eql(12)
        
        else
        pm.expect(item.Inventory).to.eql(0)
    })
})

Good luck!

2 Likes