Advanced Assertions
We have already seen different assertions and they are the common assertions that are mainly used for testing, but now let’s look at some advanced assertions.
In Postman we are keen to test our response and we can get the Json response by pm.response.json(), using this the Json Data is returned and now we can validate any property or any object.
Let our response looks something like:
1. Now, let’s start with checking whether the email is proper or not with the help of Regex Pattern
pm.test(“Regular Expression Matching”, function () {
const responseText = pm.response.json();
const regexPattern = /^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$/; // A pattern for a format like “ABC-123”
pm.expect(responseText.email).to.match(regexPattern);
});
2. Next, we are going to check if is there any greeting is there, we can check this by looking at the string that whether it contains the word “unread“.
pm.test(“Any Greeting”, function () {
const responseText = pm.response.json();
pm.expect(responseText.greeting).to.include(“unread”);
});
3. We have checked whether the email is valid or not, and now we will check whether the domain of mail is the same as the name of the company.
pm.test(“Email Domain and Company Name is Same”, function () {
const responseText = pm.response.json();
const email = responseText.email;
//Extracting the domain
const domain = email.split(‘@’)[1].split(‘.’)[0];
pm.expect(domain).to.equal(responseText.company.toLowerCase())
});
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.