Asserts in Postman

The assertion checks whether the given predict is true or false in any programming language. A predict is a Boolean expression with the value true or false. That means assertion is nothing but code that can be used to check or analyze the response that is received from the server.

An assertion is a code written in javascript in Postman that is executed after receiving the response.

Why we use Assertion in Postman

The main purpose of the test is to determine whether a given parameter of the system is working or not. To apply the force on the function parameters, we assert the predicted values during a test run with the actual values.

Assertions help us to assert that expected and actual values should match during a test run. If the actual and expected values don't match, then the test will fail with the output pointing to the failure.

In Postman, we can write the assertion in many ways. One of the simplest ways is the snippets, which are nothing but a block of codes that have some unique functions inside it and are available in the postman app. Users can easily access the snippets and can get the code inside the tests editor and run the test.

Example

Here we will discuss assertions that are primarily based on responses in the format of .json.

In Postman, an assertion can be applied on different attributes such as an object, arrays, etc.

As we know by default in Postman, the received response from the server is displayed in the JSON format, or even we can select the JSON application and get the response converted into the JSON format.

First of all, enter the following URL in the URL text field:

https://reqres.in/api/users?page=2

Send the request and see the response:

Asserts in Postman

Now add the following line of code in the test tab of the given request.


Asserts in Postman

The code pm.response.json() is used to parse the JSON body. And console.log(jsonData.data) code is used for logging the object into the Postman console.

Now, rerun the request and open the postman console.

Asserts in Postman

In the above image, you can see the arrays inside the object. Various objects are listed numbered from 0 to 5, so there were six different objects.

We can access the name and value of the array with the help of the dot (.) operator.

Edit the tests editor with the following line of code and see the console:


Asserts in Postman
Asserts in Postman

Here, you can see the value of the id, which belongs to index 2 of the array.






Latest Courses