How to Assert Response Body in Postman Tests
In Postman, you assert the response body by writing JavaScript code in the
Tests tab using the pm.response.json() method to parse the response and pm.expect() to check values. This lets you verify if the response contains expected data or structure.Syntax
To assert the response body in Postman, use the following pattern:
pm.response.json(): Parses the JSON response body.pm.expect(actual).to.eql(expected): Checks if the actual value equals the expected value.pm.expect(actual).to.have.property('key'): Checks if a property exists in the response.
javascript
const responseJson = pm.response.json(); pm.expect(responseJson.key).to.eql('expectedValue');
Example
This example shows how to assert that the response body contains a user object with a specific name and an id property.
javascript
pm.test('Response has user with name John', () => { const responseJson = pm.response.json(); pm.expect(responseJson.user.name).to.eql('John'); pm.expect(responseJson.user).to.have.property('id'); });
Output
PASS Response has user with name John
Common Pitfalls
Common mistakes when asserting response body in Postman include:
- Not parsing the response JSON before accessing properties, causing errors.
- Using incorrect property names or paths that don't match the response structure.
- Using
pm.response.text()instead ofpm.response.json()for JSON responses.
Always check the response format and parse accordingly.
javascript
/* Wrong: Accessing property without parsing JSON */ pm.test('Wrong assertion', () => { pm.expect(pm.response.json().user.name).to.eql('John'); // This will fail if pm.response.json() is not called properly }); /* Correct: Parse JSON first */ pm.test('Correct assertion', () => { const jsonData = pm.response.json(); pm.expect(jsonData.user.name).to.eql('John'); });
Quick Reference
| Assertion Method | Purpose | Example |
|---|---|---|
| pm.response.json() | Parse JSON response body | const data = pm.response.json(); |
| pm.expect(actual).to.eql(expected) | Check equality | pm.expect(data.id).to.eql(123); |
| pm.expect(actual).to.have.property('key') | Check property existence | pm.expect(data).to.have.property('name'); |
| pm.expect(actual).to.be.an('array') | Check type is array | pm.expect(data.items).to.be.an('array'); |
| pm.expect(actual).to.include('text') | Check string contains text | pm.expect(data.message).to.include('success'); |
Key Takeaways
Always parse the response body with pm.response.json() before asserting JSON data.
Use pm.expect() with clear matchers like to.eql() or to.have.property() for precise checks.
Check the response structure carefully to avoid accessing undefined properties.
Write assertions inside pm.test() blocks for clear test reporting.
Use the Quick Reference table to remember common assertion methods.