Types of Assertions in Postman
1. Checking the Status code or the status of the Request.
- For unauthorized users, it should give a 401-status code and for authorized it should give 200.
- If the Item is added to a database, then it should give 201.
- If any error is thrown, then a 500-status code is sent.
pm.test(“Content-Type is present”, function () {
pm.response.to.have.status(200);
});
2. Checking whether the response contains the data is in some constraints.
- If your API has filters, then the response should have only the data between those filters.
- After doing Login whether the response contains a JWT Token
3. Add Environment Variable.
- Accessing all the other APIs using one ID and the response contains that ID. So, Test can also add them into the environment variable.
var jsondata = pm.response.json();
pm.environment.set(“contactId”, jsondata._id);
4. Checking Headers and Cookies.
- If your response should have any particular Content-Type, then you can check it in tests.
- If the JWT token is passed in Cookies, then you can check it.
pm.test(“Content-Type is present”, function () {
pm.response.to.have.header(“Content-Type”,”application/json; charset=utf-8″);
});
Assertions in Postman and How to Use that in Scripting Window
Assertions are checks or validations we can include in our API requests to ensure that the response from the server meets certain criteria. These criteria could be based on the response’s status code, headers, body content, or any other aspect of the response. Postman provides a variety of built-in assertion options that we can use to validate the responses you receive during API testing. These assertions help us to confirm that our APIs are behaving as expected.
Assertions are mainly the tests that we want to execute after writing of code. In this case, when our APIs are ready, we just want to make sure that they are perfectly working or not. For this Postman provides us a Test section where we can write a test for the request. Postman test uses Chai Assertion Library BDD syntax.