Hi folks, I am vey new to postman. I have an array as response and I want to check if a specific item is present. I can find the item by its properties. I see in all the similar topics it is possible to use find() but I cannot make it work. May you please help me?
here it is an example of the response bdy:
@danny-dainton I read mean posts already and used a solution similar to what you proposed but unfortunately i also returns:
TypeError: Cannot read properties of undefined (reading ‘find’)
Without seeing what you have in the script, I’d going to be difficult to solve that.
It’s probably just a reference issue as that other question would have had a different response structure. You would need to edit that references to match your structure.
Here are two ways to test for those conditions using the JavaScript find function.
Option 1 searches on both conditions, and for the test you just need to check that the search is not undefined.
Option 2 searches for the name, and the test then checks if the isPrimary key = true in the returned object.
const response = pm.response.json();
console.log(response);
pm.test('Sales person = Chuck Norris and isPrimary = true V1', () => {
let searchV1 = response.find(obj => obj.salePerson === "Chuck Norris" && obj.isPrimary === true);
console.log(searchV1);
pm.expect(searchV1).to.not.be.undefined
})
pm.test('Sales person = Chuck Norris and isPrimary = true V2', () => {
let searchV2 = response.find(obj => obj.salePerson === "Chuck Norris");
console.log(searchV2);
pm.expect(searchV2.isPrimary).to.be.true;
})
Good practice is to make your test fail to ensure that you are not getting a false positive. For example, change the “to.be.true” to “to.not.be.true” and ensure it fails the test. You should do this with all assertions. Make it pass, then make it fail, before setting it back to pass. This way, you know the assertion is working as expected.