Search code examples
javascriptarraylistpostmannewmanpostman-testcase

How to verify array length for postman test


I have json response showing 4 values (image showing 3) for this object companies[0].salesReps How to verify postman test for total no of Sales employee and print their names on console.

x.companies[0].salesReps[0].name
x.companies[0].salesReps[1].name
x.companies[0].salesReps[2].name

list

Tried this saying undefined

emp = JSON.parse(responseBody(companies[0].salesReps));
    var listcnt = emp.length;
    console.log(listcnt)

Any thing missing :) Thanks


Solution

  • Not sure about the structure of your response body, but this should do it. Happy to adapt it, once you've posted your complete response body.

    const resBody = pm.response.json();
    
    const numberOfSalesEmployees = resBody.companies[0].salesReps.length;
    
    console.log("Number of sales employees:" + numberOfSalesEmployees);
    
    for (var i = 0; i < numberOfSalesEmployees; i++){
        console.log("Name of sales rep " + i + ": " + resBody.companies[0].salesReps[i].name);
    }
    
    pm.test("Number of sales employees is 4", function () {
        pm.expect(numberOfSalesEmployees).to.eql(4);
    });