How to write Assertions in Postman with Chai Assertion Library?


We can write Assertions in Postman with Chai Assertion Library. Assertions are added in tests to verify if the actual and expected results are similar. In case, they are dissimilar, an Assertion error gets thrown along with the cause of the error.

Boolean value of either true or false is returned by an Assertion. In Postman, Assertion is handled by Chai Assertion Library which is developed in JavaScript. It is provided in the Postman application by default.

Assertions in Postman are added under the Tests tab. The documentation of the Chai library details are present in the link − https://www.chaijs.com/.

Let us create an Assertion to verify if a specific text – Postman is present in an array of strings.

   pm.test["Text is present"], function(){
      pm.expect(['Java', 'Postman']).to.include('Postman')
   })

Output −

Let us create another Assertion to verify if an array contains elements.

   pm.test["Array contains element"], function(){
      pm.expect(['Java', 'Postman']).to.be.an('array').that.is.not .empty
   })

Output −

Let us implement an Assertion for verification of objects with eql function. This function compares properties of one object with another.

   pm.test("Equality", function(){
   let i = {
      "subject" : "Postman"
   };
   let j= {
      "subject" : "Cypress"
   };
   pm.expect(i).to.not.eql(j);

Output −

The property declared for object i is Postman while the property declared for j is Cypress. Hence not.eql Assertion gives a true result.

Updated on: 03-Aug-2021

204 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements