Assertions for API Test scripts

API Assertions

API testing is all about assertions. There are two steps to write assertions

  • Parse the response body
  • Write the test

Response body may come as a JSON, XML,HTML, Plain text or CSV. But the common format would be the JSON. In postman to parse the response body thereā€™s a builtin library ā€œpmā€

pm.response.json() will do the job!

Here are the few common assertions that might need to verify API responses.

  1. Verify the status code

     pm.test("Status code is 200", function() {
         pm.response.to.have.status(200);
     });
    
  1. Suppose you are getting below API response and you need to verify the each value returned in the JSON object. > {
                       "id": "15003",
                       "namespace": "se.cambio.featuretoggle.demo",
                        "name": "demo-feature-one",
                        "enabled": false,
                        "description": "demo feature one display Description",
                        "status": "ACTIVE",
                        "type": "INTERNAL",
                        "displayName": "demo feature one display name"
                    },
                {
                        "id": "15010",
                        "namespace": "se.cambio.featuretoggle.as",
                        "name": "as-feature-three",
                        "enabled": true,
                        "description": "Description of feature three",
                        "status": "ACTIVE",
                        "type": "INTERNAL",
                       "displayName": "AS Feature three"
               },

let jsonData = pm.response.json();
let ReleaseObject;

//Have a for loop to traverse through till you get the object with the name as in the if condition.

for (let Data of jsonData) {
    console.log(Data);
    if (Data.name == "demo-feature-one") {
        ReleaseObject = Data;
}

}

pm.test("Verify feature is release ready", function() {
pm.expect(ReleaseObject.id).to.not.be.null;  
pm.expect(ReleaseObject.namespace).to.equal("se.cambio.featuretoggle.demo");
pm.expect(ReleaseObject.enabled).to.be.false;
pm.expect(ReleaseObject.status).to.eql("ACTIVE");
pm.expect(ReleaseObject.togglestatus).to.eql("Enabled");

});

  1. Suppose you need to see all the JSON objects returned in the API response are equal to some condition. In case if you want to assert that all the results are in active status.

     var data = JSON.parse(responseBody);
     tests["Verify all the modules listed are release ready"] = !(responseBody.has("INACTIVE"));
    
  2. You may need to verify no of records in the DB is matched with the results count returned by the API.

const items = pm.response.json();
var a = (items && items.length) || 0;
console.log(a);
pm.test("Verify Release ready item count", function() {
pm.expect(a).to.equal(30, ā€˜Count must equal to 30ā€™);
});

  1. Verify returned array is empty

    //verify there are no results returned by the search API. Array is empty

    pm.test("Verify no results found", function(){ 
     pm.expect([ ]).to.be.empty;
   });
  1. Verify array includes an element that you search
    pm.test("Verify search element found in the array", function(){
    pm.expect([1,2,3]).to.include(3);`
 });
  1. Assertions of an array element

URL http://www.mocky.io/v2/5dba8cec300000b000028f82

Assertion Verify the order status of order id =3

JSON Response	{
    "companyid": 1000,
    "region": "APAC",
    "orderList": [
        {
            "id": 100,
            "orderName": "Order1",
            "validOrder": true
        },
        {
            "id": 200,
            "orderName": "Order2",
            "validOrder": false
        },
        {
            "id": 300,
            "orderName": "Order3",
            "validOrder": true
        }
    ]
}

The best approach is to traverse all the objects in the response to see the order with order id 3. This would be the optimum solution when we donā€™t know the array index of the object we want to see.

                let jsonData = pm.response.json();
                    let Order;
                    for(let filter of jsonData.orderList){
                     //console.log(filter);
            
        if(filter.orderName == "Order3"){
            Order=filter;
            console.log(Order);
        }
    }
        pm.test("verify the order status", function(){
            pm.expect(Order.orderName).to.eql("Order3"),
            pm.expect(Order.validOrder).to.be.true;
        });

8. Assertions on nested objects
URL http://www.mocky.io/v2/5dba84213000008700028f37

See the JSON response below. Our target is to verify the display status of the avator.

Response Body:

 {
     "id": 9,
     "email": "tobias.funke@reqres.in",
     "first_name": "Tobias",
     "last_name": "Funke",
     "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg",
     "rev": {
         "revid": 12334,
         "bookmarkstatus": "true",
         "noofbookmarks": 3,
         "comments": {
             "status": "active",
             "commentid": 123
         }
     },
     "limits": {
         "289283020299020202": {
             "avator": {
                 "avatorname": "zombie",
                 "count": 1,
                 "displaystatus": "yes"
             }
         }
     }
}

Assertion This test is to verify Avator Display status

 let jsonData = pm.response.json();
 //To identify the structre of the array return the jsonData result to console as below
console.log(jsonData); // check the postman console, to see the value passed to the variable jsonData.

 // you will see the array structure. as this is an object navigate to the the required property you want to verify using dot operator as below.
  console.log(jsonData.rev.comments.status);

 // Assign the status to a variable and verify  if it is active
   let commentStatus = jsonData.rev.comments.status;
   pm.test("Verify comments status", function(){
   pm.expect(commentStatus).to.eql("active");
     });
     
    //This test is to verify Avator Display status
     let AvatorStatus;
      for(let key in jsonData.limits){
          console.log(jsonData.limits[key]);
          console.log(jsonData.limits[key].hasOwnProperty("avator"));
          if(jsonData.limits[key].hasOwnProperty('avator')){
            AvatorStatus = jsonData.limits[key].avator.displaystatus;
      }
     }
    pm.test("display status is true", function(){
      pm.expect(AvatorStatus).to.eql("yes");
      });
3 Likes

Hi ,
Please help in Delete Assert
json =

[
  {
    "InterfaceGroupId": "60f9ae30b03eb7c5d8734cc9",
    "GroupName": "madhu5zb8lv6dokgroup",
    "Description": "from MOB",
    "TenantCsn": "madhucsn",
    "IsDefault": false,
    "IsDeleted": false,
    "CreationDate": null
  },
  {
    "InterfaceGroupId": "60f92584b03eb7c5d8734cc8",
    "GroupName": "madhuom4s4vokqxgroup",
    "Description": "from MOB",
    "TenantCsn": "madhucsn",
    "IsDefault": false,
    "IsDeleted": false,
    "CreationDate": null
  }
]

1.ENV variable GroupName exists in postman
2.Delete API is looking for ā€œInterfaceGroupIdā€ in the request Body
3.I want to pass that InterfaceGroupId which is in ENV variable ā€œGroupNameā€