What are Postman tests, and how to write them?

Postman is a API development and testing tool, which provides a feature called tests. These tests is used to automate the validation of API responses.

Table of Content

  • What are Postman Tests?
  • Key Features of Postman Tests
  • Writing Postman Tests

What are Postman Tests?

Postman tests are scripts written in JavaScript to automate the validation of API responses within the Postman API development environment. These tests allow developers to verify that an API is carrying as anticipated and that the responses meet certain criteria. Postman provides a testing framework that integrates with requests, enabling the execution of tests after sending a request.

Key Features of Postman Tests

  • Automated Validation: It automate the process of verifying API responses, which makes sure its accuracy and functionality.
  • Assertions: It uses assertions to check response status codes, headers, body content etc. to confirm expected behaviors.
  • Scripting Support: Postman provides a scripting environment which allows flexibility in writing test scripts.

Writing Postman Tests:

Step 1: Open the Postman and create a new collection with name ‘Postman Echo’. After that you can see different tab option below and one of them is ‘Tests’.

Note: In the right side of the Tests section you can see a list of code snippet. You can click any of the snippet according to your requirement. This makes writing Tests easily.

Step 3: Lets use a ‘Tests’ from the snippet to check if the status code of the API is 200 or not.

API used: https://postman-echo.com/get

Step 4: Now we will check if the response has content type or not and if it has then its type is application/json.

For that write the following Tests in the Tests section and click on send.

var contentTypeHeaderExists = responseHeaders.hasOwnProperty("Content-Type");

tests["Has Content-Type"] = contentTypeHeaderExists;

if (contentTypeHeaderExists) {
tests["Content-Type is application/json"] =
responseHeaders["Content-Type"].has("application/json");
}

Output: