0
0
PostmanHow-ToBeginner ยท 3 min read

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 of pm.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 MethodPurposeExample
pm.response.json()Parse JSON response bodyconst data = pm.response.json();
pm.expect(actual).to.eql(expected)Check equalitypm.expect(data.id).to.eql(123);
pm.expect(actual).to.have.property('key')Check property existencepm.expect(data).to.have.property('name');
pm.expect(actual).to.be.an('array')Check type is arraypm.expect(data.items).to.be.an('array');
pm.expect(actual).to.include('text')Check string contains textpm.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.