Check null value in Postman test cases .not.eql() or .not.equal() are not working
Asked Answered
F

1

8

I'm working with a API project and using Postman for testing APIs. I wrote few test cases to check null as follows,

//user id is present
pm.test("user id is present", function() {
    pm.expect(jsonData.data[0].userId).not.eql(null);
});

Also tried with .not.equal() as described in this answer.

//user id is present
pm.test("user id is present", function() {
    pm.expect(jsonData.data[0].userId).not.equal(null);
});

However, this all are getting passed even if the userId is null. Any furhter thought to check null value in Postman test case?

Fajardo answered 28/1, 2019 at 8:50 Comment(3)
.to.not.be.null? chaijs.com/api/bdd/#method_null But it always says in the docs that this is not recommend...Amye
@DannyDainton: Tried .to.not.be.null however, no luck so far. Yes, I checked doc already, but then what is alternative?Fajardo
Just trying to find something locally that works. Seems like nothing I've tried (each example I've come across) gives me the result I want. :( This feels like it should be so difficult...but it's proving to be. :(Amye
S
8

First of all, open the console and run the flowing snippet to check the types:

pm.test("user id is present", function() {
   console.log(typeof jsonData.data[0].userId);
   console.log(typeof jsonData.data[0]);
   console.log(typeof jsonData);
}

If you get undefined for jsonData.data[0].userId, you need change your test to assert null and undefined:

pm.test("user id is present", function() {
   pm.expect(jsonData.data[0].userId).to.exist //check if it is not equal to undefined
   pm.expect(jsonData.data[0].userId).to.not.be.null; //if it is not equal to null
}
Sharkey answered 28/1, 2019 at 15:25 Comment(9)
Very odd this problem, I made some tests in my postman and worked fine. My version is 6.7.2Sibling
Did you parse your JSON data with JSON.parse?Sibling
using pm.response.json();Fajardo
Try this: pm.expect(jsonData.data[0].userId).to.satisfy(function (userId) { if (userId === null) { return false; } else { return true } });Sibling
Thanks Ângelo, I will surly try this and let you know, see you tomorrow!Fajardo
Can you run this snippet and send the result to me? console.log(typeof jsonData.data[0].userId); console.log(typeof jsonData.data[0]); console.log(typeof jsonData);Sibling
undefined, object, objectFajardo
Okay, so I have to check with undefined instead of null i.e .not.eql(undefined)Fajardo
Exactly! I will change the answer and add all the main points of this discussion.Sibling

© 2022 - 2024 — McMap. All rights reserved.