0
0
PostmanHow-ToBeginner · 4 min read

How to Use pm.expect in Postman for API Testing

In Postman, use pm.expect to write assertions that check if your API response meets expected conditions. It works like a test assertion library, letting you verify status codes, response times, or data values easily within your test scripts.
📐

Syntax

The basic syntax of pm.expect is similar to assertion libraries in JavaScript. You call pm.expect(actualValue) and chain it with an assertion method like .to.eql(expectedValue) or .to.have.property('key').

Here’s what each part means:

  • pm.expect(): Starts the assertion with the actual value you want to test.
  • .to: Chains the assertion to specify the condition.
  • .eql(value): Checks if the actual value equals the expected value.
  • .have.property('key'): Checks if an object has a specific property.
javascript
pm.expect(actualValue).to.eql(expectedValue);
pm.expect(object).to.have.property('key');
💻

Example

This example shows how to check if the response status code is 200 and if the JSON response has a property success set to true.

javascript
pm.test('Status code is 200', () => {
    pm.expect(pm.response.code).to.eql(200);
});

pm.test('Response has success property true', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('success', true);
});
Output
PASS Status code is 200 PASS Response has success property true
⚠️

Common Pitfalls

Common mistakes when using pm.expect include:

  • Not parsing JSON response before checking properties (use pm.response.json()).
  • Using incorrect assertion methods or chaining syntax.
  • Confusing .to.eql() (deep equality) with .to.equal() (shallow equality).

Example of wrong vs right usage:

javascript
// Wrong: Checking property on raw response text
pm.test('Wrong property check', () => {
    pm.expect(pm.response.text()).to.have.property('success'); // This will fail
});

// Right: Parse JSON first
pm.test('Correct property check', () => {
    const data = pm.response.json();
    pm.expect(data).to.have.property('success');
});
Output
FAIL Wrong property check PASS Correct property check
📊

Quick Reference

AssertionDescriptionExample
to.eql(value)Checks deep equalitypm.expect(5).to.eql(5);
to.equal(value)Checks shallow equalitypm.expect('abc').to.equal('abc');
to.have.property(key)Checks object has propertypm.expect(obj).to.have.property('name');
to.be.above(number)Checks number is greaterpm.expect(10).to.be.above(5);
to.be.trueChecks value is truepm.expect(flag).to.be.true;

Key Takeaways

Use pm.expect to write clear assertions in Postman test scripts.
Always parse JSON responses before checking properties with pm.response.json().
Chain assertion methods like .to.eql() or .to.have.property() for specific checks.
Common errors include checking raw text instead of parsed JSON and wrong assertion chaining.
Refer to common assertion methods to validate status codes, response data, and types.