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 : "playerReference":"+33123456789"
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
I tried something like that
if(pm.expect(jsonData.playerReference).to.be.an('undefined') === true) {
console.log("there is no player reference");
}
else
{
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");
}
else
{
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 ?
[RESOLVED]
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");
}
else
{
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");
});
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
EDIT:
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();
body.hasOwnProperty("loginInformation");
// This will output true
body.hasOwnProperty("session");
// This will output false as we're only looking at the top-level of the response, any nested objects won't return true.
body.loginInformation.hasOwnProperty("session");
// This will now output true