Search code examples
javascriptpostmanpostman-testcase

How to verify the length of attributes in an array and make sure no extra attributes are displayed?


I have verified the length of input as var resp =(body.input).length and make sure it is not 0. But I also want to verify only firstname,lastname and rollno is available in each set and the count will be always 3. How to I verify this is postman Test?

Response body:

{
"success": true,
"input":[
{
    firstname:"Ram"
    lastname:"Lakshmanan"
    rollno: "11"
},
{
    firstname:"Pravi"
    lastname:"Reshma"
    rollno: "12"
}
]
}

My Test looks like below:

var i;
for(i=0 ; i< resp ; i++){

   var resp_firstname = body.input[i].firstname;

   pm.test("Verify first name is available and not empty",function(){
      pm.expect(resp_firstname).to.exist;
      pm.expect(resp_firstname).to.not.eql();
}

Solution

  • First of all response body provided in the question is not the valid JSON.
    Valid json data should look like this =

    {
       "success":true,
       "input":[
          {
             "firstname":"Ram",
             "lastname":"Lakshmanan",
             "rollno":"11"
          },
          {
             "firstname":"Pravi",
             "lastname":"Reshma",
             "rollno":"12"
          }
       ]
    }
    

    you could do it like-

    pm.test("Verify object has expected properties", function () {
        // loop through input array
        for (var i = 0; i < Object.keys(json.input).length; i++) {
            console.log(i);
            pm.expect(json.input[i]).to.have.property("firstname");
            pm.expect(json.input[i]).to.have.property("lastname");
            pm.expect(json.input[1]).to.have.property("rollno");
            //assert length of properties
            pm.expect(Object.keys(json.input[i]).length).to.eql(3);
        }
    });