Check each nested object contains a value in one of two objects

Test that each nested and unnamed object has prior=248 or new=248

I am trying to write a test that checks each of the objects in the JSON response body for a specific string (in this case ‘248’) in either the ‘changes.prior’ or ‘changes.new’ field.

Here is an example JSON response body:

[
    {
        "eventType": "account-updated",
        "changes": [
            {
                "property": "preferredStoreId",
                "prior": "248",
                "new": "20"
            }
        ]
    },
    {
        "eventType": "account-updated",
        "changes": [
            {
                "property": "preferredStoreId",
                "prior": "265",
                "new": "248"
            }
        ]
    }
]

I reviewed this post and attempted these test scripts, neither of which works:

pm.test("Each event contains search param", () => {
    require('lodash').each(jsonData, (item) => {
        pm.expect(item.changes.prior || item.changes.new).to.contain('248')
    })
})

pm.test('Each event contains search param', () => {
    require('lodash').each(jsonData, (item) => {
        pm.expect(item.changes.prior.contain("248") || item.changes.new.contain("248")).to.be.true
    })
})

I believe the outer [brackets] are confusing me. Can anyone help me with a test like this?

Changes is an array, so you need to target it with its array index.

Indexes start at zero, so it would be changes[0].

Postman uses ChaiJS for its assertion library, so its always useful to look at the examples.

The following test should meet your criteria.

const response = pm.response.json();

response.forEach((obj, i) => {
    let cNew = obj.changes[0].new; // new is a reserved word
    let prior = obj.changes[0].prior;
    pm.test(`Object ${i} prior[${prior}] or new[${cNew}] = 248 `, () => {
        pm.expect(new Set([cNew, prior])).to.include("248");
    })
});

I added a third object that didn’t meet the criteria so you could see the test failing.

I’m using the array index to customize the test case name, so you know which object has failed.

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.