Look if a property exists in responseBody

Hi guys,

I’m trying to do something that seems to be a little more complicated than I thought.

Here’s the thing. For a specific request, sometimes my response body will contain :
and sometimes, not. I’m not saying that sometimes “playerReference” is null, but it is simply NOT in the response body. And I want to create a condition on wether or not “playerReference” exists and I can’t :frowning:

I tried something like that

if(pm.expect(jsonData.playerReference).to.be.an('undefined') === true) {
    console.log("there is no player reference");
    console.log("there is a player reference");

Or even

if(pm.expect(pm.response.text()).to.include('playerReference') === true) {
    console.log("there is player reference");
    console.log("there is no player reference");

I really don’t understand why the last one doesn’t work.

Postman documentation is usually really helpful on this topic. However, I’m struggling to find a proper solution to my problem, here.

Any ideas ?


I changed my condition to simple javascript and now it’s working

if(pm.response.text().includes('playerReference') === true) {
    console.log("there is a player reference");
    console.log("there is no player reference");

I’m about to leave work, so I’ve only skim-read your post - sorry if this isn’t what you want.

But you could use the “hasOwnProperty” method.

if(pm.response.json().hasOwnProperty("playerReference") {
   console.log("The property is there!");
} else {
  console.log("The property isn't there :(");

I always test for properties/values like this:

const body = pm.response.json();
// The below will fail and give us a helpful failure message if "playerReference" is NOT present
// And it'll also give us a helpful failure message if the value of "playerReference" is NOT "123"
pm.test("Property is there", function() {
  pm.expect(body).to.have.property("playerReference", "123");

Right! Home time for me :slight_smile:

1 Like

I didn’t know about hasOwnProperty
I also have to head home so I’ll test it tomrrow :slight_smile:
Thank you sharing it !

hey @steven_kp Did the code snippet work for you?

Hello pfarrel,

In my case, hasOwnProperty doesn’t seem to work. It returns me false even though the property is there…

Anyway, I found a workaround using pm.response.text() and .includes()

Thank you :slight_smile:

Actually it is working. I did a test with a property that was inside another property, hence the error.
“loginInformation”: {
“session”: “99456489” }
If I do hasOwnProperty(“loginInformation”), I’ve got true. However, if I do hasOwnProperty(“session”), I’ve got false

Yep, that’s because the “session” property, is inside the “loginInformation” object.

So if you did:

const body = pm.response.json();
// This will output true
// This will output false as we're only looking at the top-level of the response, any nested objects won't return true.
// This will now output true