I want to check in my JSON response Array if a key:value exists. and I want if the key:value is found get out from the loop and get the test result. Can you please support me how to do it?
e.g. I have the following response:
[
{
"persID": "personID_1",
"vip": false,
"account": {
"contactName": "value1",
},
"premium": {
"Name": "value2",
"Director": "value3",
"company": "value7",
"homePage": "value6",
"address": {
"country": "value8",
"city": "value9"
},
"photo": value10
}
},
{
"persID": "personID_2",
"vip": false,
"account": {
"contactName": "value11",
},
"premium": {
"Name": "value12",
"Director": "value13",
"company": "value17",
"homePage": "value16",
"address": {
"country": "value18",
"city": "value19"
},
"photo": value110
}
},
.....
.....// dynamic response can be "n" elements!!!!
]
and I want to check if in this array a key value with ("persID": "personID_3") exist. (e.g. for persID_3, should the result be failed, and persID_2 passed)
I have tried the following but no result:
var jsonArray = pm.response.json();
var persID = "persID_3";
pm.test("2. tets check if persdID exist in array", function () {
var i=0;
for(i; i<jsonArray.length;i++){
pm.expect(jsonArray).to.have.property(jsonArray[i].persID, persID);
// pm.expect(jsonArray[i]).to.have.property(jsonArray[i].persID, persID);
}
});
Also tried with var jsonArray = JSON.parse(responseBody); and pm.expect(jsonArray[i]).to.have.property(jsonArray[i].persID, persID);
but no result
Thanks for any Support.
You could use Lodash to loop through the array and check for the value in the response:
pm.test('Matches personID property value', () => {
_.each(pm.response.json(), (arrItem) => {
if (arrItem.persID === 'personID_2') {
throw new Error(`Array contains ${arrItem.persID}`)
}
})
});
This should fail the test if the personID_2
property exists but this value could be anything you like. I used your response data and created a quick API route to show you this working.
I added the value in to the Error message so that it is more descriptive on the test output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With