34

I want to know how can I test if an object exists. For example, my API return these things :

"data": [
    {
      "id": 1,
      "name": "Abu Dhabi",
      "locale": "AE",
      "rentWayCountryId": 242,
      "stations": [
        {
          "id": 2,
          "rentWayName": "ABU DHABI AIRPORT",
          "rentWayStationId": "IAEAUH1",
          "bindExtrasToStationToExtraCategory": []
        }
      ]
    },

I want to check that data.id exists.

I used the test options in postman and i did this :

var jsonData = JSON.parse(responseBody);
tests["Name value OK"] = jsonData.data.id === "1";

Could you tell me which condition should I use to verify only if the data exist?

Thank you very much !!

monkrus
  • 1,470
  • 24
  • 23
Mehdy Driouech
  • 401
  • 1
  • 4
  • 6

5 Answers5

96

Here is a proper Postman test:

const jsonData = pm.response.json();

pm.test('Has data', function() {
  pm.expect(jsonData).to.have.property('data');
});

The above will either PASS or FAIL yor postman request based on the presence of the data property in the response.

EricWasTaken
  • 1,654
  • 14
  • 19
7

To check whether the object is exist or not is equivalent to check whether it is null or not.

if(object){//runs if object is not null}
Abdullah Danyal
  • 1,106
  • 1
  • 9
  • 25
6

Thanks for the idea ! i tried this :

var jsonData = JSON.parse(responseBody);
tests["idExist"] = jsonData.data.id !== null ;

and it worked. Thanks very much

Mehdy Driouech
  • 401
  • 1
  • 4
  • 6
  • 3
    Hello and welcome to StackOverflow Mehdy :) If you find an answer that answers your question we suggest that you 'accept' it by clicking the tick option next to it. This shows other developers quickly the correct solution. It also helps you and the answerer earn a small amount of reputation (the points next to your name). – Ray May 15 '17 at 09:58
2

If you need to check if variable is being set, use this solution:

tests["idExist"] = pm.globals.get('dealerId') !== undefined;
uBaH
  • 169
  • 1
  • 12
1
jsonData = pm.response.json();

pm.test("Expected response to be an object", function () {
    pm.expect(jsonData).to.be.an('object');
});

pm.test('Has property inside object', function() {
  pm.expect(jsonData.data[0]).to.have.property('id');
});

pm.test("Expected jsonData[0].stations to be an array", function () {
    pm.expect(jsonData[0].stations).to.be.an('array');
});
pm.test("Expected elements inside jsonData[0].stations to have keys", function () {
    pm.expect(jsonData[0].stations).to.have.keys("id","rentWayName",
          "rentWayStationId",
          "bindExtrasToStationToExtraCategory");
});
David
  • 307
  • 3
  • 7