I have a response with the following body, an array.
I want to check that we have an item and only one with value IsPrimary true and salePerson of value ‘Chuck Norris’.
[
{
"districtName": "Austria",
"storeName": "Store6",
"salePerson": "sdfgh",
"isPrimary": false
},
{
"districtName": "Austria",
"storeName": "Store6",
"salePerson": "dfsd",
"isPrimary": false
},
{
"districtName": "Austria",
"storeName": "Store6",
"salePerson": "Chuck Norris",
"isPrimary": true
},
{
"districtName": "Austria",
"storeName": "Store6",
"salePerson": "sdfgh",
"isPrimary": false
}
I tried with filtering it gave me error:
data =pm.response.body;
let object_to_find = { saleperson: 'Chuck Norris' };
let result2 = data.filter(function (value) {
return value.id == object_to_find.id && value.name == object_to_find.name;
});
console.log(result2);
Error:
Couldn't evaluate the test script:
TypeError: Cannot read properties of undefined (reading 'filter')
2
Answers
To filter the array based on a specific condition (in your case, looking for an item with salePerson as ‘Chuck Norris’ and isPrimary as true), you can use the filter function as follows:
Also ensure that the response body (pm.response.body) is properly parsed into a JavaScript object using pm.response.json() before applying the filter function and confirm that the property names used for comparison (salePerson, isPrimary) match exactly with those in the response object.
@Doraemon There are two improvements needed in this particular case.
brace) is missing.
the tests (thats where I found the array closing issue) and test can
be improved as
`
`
Attaching below the screenshot from local