How to verify array length for postman test

4.1k views Asked by At

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

2

There are 2 answers

5
Christian Baumann On BEST ANSWER

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);
});
1
Chrisanthemum On

I think you'd be better off parsing responseBody first (before trying to access data in the response), so:

var parsedResponseBody = JSON.parse(responseBody);
var listCnt = parsedResponseBody.companies[0].salesReps.length;