0
0
PostmanHow-ToBeginner ยท 3 min read

How to Assert Status Code in Postman Tests

In Postman, you assert the status code by writing a test script using pm.response.to.have.status(code). This checks if the response status matches the expected code, such as 200 for success.
๐Ÿ“

Syntax

The basic syntax to assert a status code in Postman test scripts is:

  • pm.response.to.have.status(code): Checks if the response status code equals code.
  • code can be a number like 200, 404, or a string like 'OK'.
javascript
pm.test('Status code is 200', () => {
  pm.response.to.have.status(200);
});
๐Ÿ’ป

Example

This example shows how to assert that the response status code is 200, which means the request was successful.

javascript
pm.test('Status code is 200', () => {
  pm.response.to.have.status(200);
});
Output
PASS - Status code is 200
โš ๏ธ

Common Pitfalls

Common mistakes when asserting status codes in Postman include:

  • Using a string instead of a number for the status code, e.g., pm.response.to.have.status('200') instead of 200.
  • Not wrapping the assertion inside pm.test(), which means the test won't run or report properly.
  • Expecting the wrong status code for the API endpoint, causing false test failures.
javascript
/* Wrong way: Using string instead of number */
pm.test('Status code is 200', () => {
  pm.response.to.have.status('200'); // This may fail
});

/* Right way: Use number */
pm.test('Status code is 200', () => {
  pm.response.to.have.status(200);
});
๐Ÿ“Š

Quick Reference

Here is a quick cheat-sheet for asserting status codes in Postman:

AssertionDescription
pm.response.to.have.status(200)Asserts response status is 200 OK
pm.response.to.have.status(404)Asserts response status is 404 Not Found
pm.response.to.have.status('Created')Asserts response status is 201 Created (string name)
pm.test('Check status', () => { ... })Wraps assertions to run as a test
โœ…

Key Takeaways

Always use pm.test() to wrap your status code assertions in Postman.
Use numeric status codes like 200, 404 for clear and reliable checks.
Avoid using strings for status codes unless using standard status text names.
Check the API documentation to know the expected status code for each request.
Clear and simple assertions help quickly identify API response issues.