How to check if an object exist in POSTMAN?

Viewed 47277

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 !!

5 Answers

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.

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

tests["idExist"] = pm.globals.get('dealerId') !== undefined;
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");
});
Related