0
0
Postmantesting~15 mins

Response body array assertions in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify response body contains expected array elements
Preconditions (2)
Step 1: Send a GET request to https://api.example.com/users
Step 2: Check that the response status code is 200
Step 3: Verify the response body is an array
Step 4: Verify the array contains at least one user object with 'id' equal to 1
Step 5: Verify each user object has 'id', 'name', and 'email' properties
✅ Expected Result: The response status code is 200, the response body is an array, it contains a user with id 1, and all user objects have the required properties
Automation Requirements - Postman Tests (JavaScript)
Assertions Needed:
Status code is 200
Response body is an array
Array contains an object with id = 1
Each object has 'id', 'name', and 'email' properties
Best Practices:
Use pm.response.to.have.status for status code assertion
Parse response JSON once and reuse
Use Array methods like some() and every() for array assertions
Write clear and descriptive assertion messages
Automated Solution
Postman
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

const jsonData = pm.response.json();

pm.test('Response body is an array', () => {
    pm.expect(Array.isArray(jsonData)).to.be.true;
});

pm.test('Array contains a user with id = 1', () => {
    const hasUserId1 = jsonData.some(user => user.id === 1);
    pm.expect(hasUserId1, 'User with id 1 should exist').to.be.true;
});

pm.test('Each user has id, name, and email properties', () => {
    const allHaveProps = jsonData.every(user => 
        user.hasOwnProperty('id') && user.hasOwnProperty('name') && user.hasOwnProperty('email')
    );
    pm.expect(allHaveProps, 'All users should have id, name, and email').to.be.true;
});

This test script uses Postman’s built-in pm object to write assertions.

First, it checks the status code is 200 to confirm the request succeeded.

Then it parses the response JSON once and stores it in jsonData for reuse.

It asserts the response is an array using Array.isArray().

Next, it uses some() to check if any user object has id equal to 1.

Finally, it uses every() to verify all user objects have the required properties id, name, and email.

Each assertion has a clear message to help understand test results.

Common Mistakes - 4 Pitfalls
Not checking the status code before parsing response body
Parsing response JSON multiple times
Using hardcoded indexes to check array elements
Not verifying all required properties exist on objects
Bonus Challenge

Now add data-driven testing with 3 different user IDs to verify each exists in the response array

Show Hint