Home > Software design >  Unit Test to find a keyword in a response array
Unit Test to find a keyword in a response array

Time:10-28

good day everyone, i am new here,

I have a response data looking like this

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

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 == 12", () => {
    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

CodePudding user response:

why can't you just compare the object as it is than individual fields ? as you are comparing exact values.

let expected = [
    {
        "Outlet": "Outlet1",
        "Inventory": 12
    },
    {
        "Outlet": "Outlet2",
        "Inventory": 0
    },
    {
        "Outlet": "Outlet3",
        "Inventory": 3
    },
    {
        "Outlet": "Outlet4",
        "Inventory": 0
    }
]

pm.expect(JSONdata).to.be.deep.eq(expected1, `Expected ${JSON.stringify(JSONdata,null,2)} to be equal to ${JSON.stringify(expected,null,2)}`)

CodePudding user response:

Other way would be :

pm.test("Validate inventory values", () => {
    jsonData.forEach(function (item) {
        if (item.Outlet !== "Outlet1") {
            pm.expect(item.Inventory,
                `Expected inventory value of ${item.Outlet} to be 0`).
                to.
                eql(0)
        } else {
            pm.expect(item.Inventory,
                `Expected inventory value of ${item.Outlet} to be 12`).
                to.
                eql(12)
        }
    })
});
  • Related