Check key/value pair exists in each twice-nested array

Test that each changes array has property = active

I am trying to write a test that checks each changes object in the JSON response body for property = active.

In other words, each changes array within the response should have the key/value pair "property": "active" (regardless of accompanying key/value pairs).

Here is an example JSON response body:

[
    {
        "eventType": "account-created",
        "changes": [
            {
                "property": "email",
                "new": "tc1583181_71724a@yopmail.com"
            },
            {
                "property": "firstName",
                "new": "TestCase"
            },
            {
                "property": "active",
                "new": "true"
            }
        ]
    },
    {
        "eventType": "account-deactivated",
        "changes": [
            {
                "property": "active",
                "prior": "true",
                "new": "false"
            },
            {
                "property": "updatedAt",
                "prior": "2024-07-17T17:55:34.583",
                "new": "2024-07-17T17:55:34.590"
            }
        ]
    }
]

I have read several posts but solutions do not fit the weird formatting of the JSON, the nature being so very nested inside of unnamed brackets. I did recently ask a similar question which got me half way to this failing attempt:

var jsonData = pm.response.json();
jsonData.forEach((obj, i) => {
    let changes = obj.changes[0].property;
    changes.forEach((objb, j) => { //FAILS - TypeError: changes.forEach is not a function
        let attr = objb.property[0];
        pm.test(`Object ${i} property[${j}] = active `, () => {
            pm.expect(attr).to.include("active");
        })
    })
});

Can anyone help me with a test like this?

Changes is an array with multiple properties, but as you don’t know the array index for the property you want to check, you need to search the array for that property and just test that the search is not undefined.

var response = pm.response.json();

response.forEach((obj, i) => {
    let search = (obj.changes.find(change => { return change.property === "active" }));
    // console.log(search);
    pm.test(`Object ${i} changes array includes "active" property`, function () {
        pm.expect(search).to.not.be.undefined
        pm.expect(search.property).to.eql("active"); // this assertion is not needed
    });
});

image

I changed the property on the first object, so you can see the test failing.

1 Like

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