0
0
Postmantesting~15 mins

Response body assertions in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify response body contains expected user data
Preconditions (2)
Step 1: Send a GET request to https://api.example.com/users/123
Step 2: Check the response status code is 200
Step 3: Verify the response body contains a JSON object with keys: id, name, email
Step 4: Verify the id value is 123
Step 5: Verify the name value is 'John Doe'
Step 6: Verify the email value is 'john.doe@example.com'
✅ Expected Result: Response status code is 200 and response body JSON contains correct user data as specified
Automation Requirements - Postman Tests
Assertions Needed:
Status code is 200
Response body has keys: id, name, email
id equals 123
name equals 'John Doe'
email equals 'john.doe@example.com'
Best Practices:
Use pm.response.to.have.status for status code assertion
Use pm.response.json() to parse response body
Use strict equality checks for values
Write clear and descriptive assertion messages
Automated Solution
Postman
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

pm.test('Response body has expected user data', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.all.keys('id', 'name', 'email');
    pm.expect(jsonData.id).to.eql(123);
    pm.expect(jsonData.name).to.eql('John Doe');
    pm.expect(jsonData.email).to.eql('john.doe@example.com');
});

The first test checks that the response status code is exactly 200 using pm.response.to.have.status(200). This ensures the request was successful.

The second test parses the response body JSON with pm.response.json(). It then asserts the JSON object has all the keys id, name, and email using to.have.all.keys. This confirms the expected data structure.

Finally, it checks each key's value matches the expected data using strict equality to.eql(). This verifies the correctness of the response content.

Each assertion has a clear message to help identify failures during test runs.

Common Mistakes - 4 Pitfalls
Not checking the status code before validating response body
Using loose equality (==) instead of strict equality (=== or to.eql) in assertions
Not parsing the response body JSON before accessing keys
Hardcoding values without verifying the response structure first
Bonus Challenge

Now add data-driven testing with 3 different user IDs and expected user data

Show Hint