We check arrays in response bodies to make sure the data we get is correct and complete. This helps us trust the API works as expected.
Response body array assertions in Postman
pm.test("Test description", function () { let jsonData = pm.response.json(); pm.expect(jsonData.arrayName).to.be.an('array'); pm.expect(jsonData.arrayName).to.have.lengthOf(expectedLength); pm.expect(jsonData.arrayName).to.include(expectedValue); pm.expect(jsonData.arrayName[0]).to.have.property('propertyName'); });
Use pm.response.json() to parse the response body as JSON.
Use pm.expect() with Chai assertions to check array properties.
pm.test("Response has an array called users", function () { let jsonData = pm.response.json(); pm.expect(jsonData.users).to.be.an('array'); });
pm.test("Users array has 3 items", function () { let jsonData = pm.response.json(); pm.expect(jsonData.users).to.have.lengthOf(3); });
pm.test("Users array includes a user named 'Alice'", function () { let jsonData = pm.response.json(); let userNames = jsonData.users.map(user => user.name); pm.expect(userNames).to.include('Alice'); });
pm.test("First user has an 'id' property", function () { let jsonData = pm.response.json(); pm.expect(jsonData.users[0]).to.have.property('id'); });
This test checks that the response has an 'items' array with exactly 2 elements. It also verifies that one of the items is named 'Book' and that the first item has a 'price' property.
pm.test("Validate response body array assertions", function () { let jsonData = pm.response.json(); // Check 'items' is an array pm.expect(jsonData.items).to.be.an('array'); // Check array length is 2 pm.expect(jsonData.items).to.have.lengthOf(2); // Check array includes an item with name 'Book' let itemNames = jsonData.items.map(item => item.name); pm.expect(itemNames).to.include('Book'); // Check first item has 'price' property pm.expect(jsonData.items[0]).to.have.property('price'); });
Array assertions help catch errors early by confirming the structure and content of response data.
Common mistake: Forgetting to parse the response body as JSON before assertions.
Use array assertions when you expect multiple items, and use object assertions for single items.
Response body array assertions check if the API returns the correct list of items.
We verify array type, length, contents, and properties of items inside.
These checks help ensure the API data is reliable and complete.