Test to see if value exists

Hello,

I am still new to postman and JSON and get confused easily what is an array/object and how to correctly work with them.

I have a test script which works

let jsonData = pm.response.json()
pm.environment.set(ā€œUserVarā€, pm.response.json()[0].member.criteria.children[3].key.sourceId);

This works and pulls a value like this
2c9180897a5eb28b017a

but what I want to achieve - I want to create a Test which tell me if that value is located anywhere in any of the response: 2c9180897a5eb28b017a

I tried many thingsā€¦ but the one I feel is closest, I tried the following but it does NOT work it gives me an ā€œAssertionError: Target cannot be null or undefined.ā€

pm.test(ā€˜Test to find valueā€™, () => {
pm.expect(jsonData.key).have.property(ā€˜sourceIdā€™, ā€˜2c9180897a5eb28b017aā€™);
});

Hi, I think this topic can help you with what you need, but if you canā€™t let me know Iā€™ll help :wink:

I couldnā€™t get that to work @cmnazario
But thank you for the help.

I did find a solution, so Iā€™m going to post it, to hopefully help someone else in the future.
Rather than searching through objects and arrays and confusing myself what-is-what.

I put this in the Tests tab.

string = JSON.stringify(pm.response.json());
if(pm.expect(string).to.include(ā€˜2c9180897a5eb28b017aā€™)){
pm.test(ā€œsuccessā€)
}
else{
pm.test(ā€œfailā€)
}

It will output in the console ā€œsuccessā€ if it finds the string
It outputs a big red error in the fail scenario
ā€œerror in evaluating the test script: AssertionError: expectedā€

But honestlyā€¦ I spent enough time on this for nowā€¦ so this works fine for what I was trying to achieve.

2 Likes