top of page
vijetha.asam

Assertions in Postman with Chai Assertion Library

Assertion:


  • At the basic level, an assertion is just a Boolean expression. It contains a true and false binary.


  • Assertion is a key concept in functional testing. In essence, assertions are used to declare the expected behavior or outcome of a test.


  • Assertion is used in functional testing in two ways. Testers can make use of hard or soft assertions.


  • With a hard assertion, any system error that causes the assertion to return a false result will stop the execution. Further steps in the execution will not go forward unless it is manually restarted. On the other hand, a soft assertion means that the execution will keep going forward and proceed through all further steps in the chain, even when the assertion has returned a false result due to an error.


What is chai assertion?


  • Chai assertion library is an external javascript library used to write assertions.. Compared to what we write directly in javascript, this assertion library needs less time & effort and easy use.


  • Chai assert is used to verify whether a given expression or value meets certain conditions.


  • We can make assertions like checking type, presence, length and more.



Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

Chai is available for both node.js and the browser using any test framework you like.

There are also a number of other tools that include Chai.

Chai can be used with various testing frameworks like Mocha, Jasmine and Jest.


Chai assertion library is available by default in the Postman:

Assertion Styles:


Assert

The assert style is exposed through assert interface. This provides the classic assert-dot notation, similar to that packaged with node.js. This assert module, however, provides several additional tests and is browser compatible.

Example:


var assert = require('chai').assert

  , foo = 'bar'

  , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };

assert.typeOf(foo, 'string'); // without optional message

assert.typeOf(foo, 'string', 'foo is a string'); // with optional message

assert.equal(foo, 'bar', 'foo equal `bar`');

assert.lengthOf(foo, 3, 'foo`s value has a length of 3');

assert.lengthOf(beverages.tea, 3, 'beverages has 3 types of tea');


Expect

The BDD style is exposed through expect or should interfaces. In both scenarios, you chain together natural language assertions.

Example:


var expect = require('chai').expect

  , foo = 'bar'

  , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };

expect(foo).to.be.a('string');

expect(foo).to.equal('bar');

expect(foo).to.have.lengthOf(3);

expect(beverages).to.have.property('tea').with.lengthOf(3);


Should

The should style allows for the same chainable assertions as the expect interface, however it extends each object with a should property to start your chain. This style has some issues when used with Internet Explorer, so be aware of browser compatibility.

Example:


var should = require('chai').should() //actually call the function

  , foo = 'bar'

  , beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };

foo.should.be.a('string');

foo.should.equal('bar');

foo.should.have.lengthOf(3);

beverages.should.have.property('tea').with.lengthOf(3);


Expect and Should:

The BDD styles are expect and should. Both use the same chainable language to construct assertions, but they differ in the way an assertion is initially constructed. Check out the Style Guide for a comparison


Language Chains

The following are provided as chainable getters to improve the readability of your assertions.

Chains

  • to

  • be

  • been

  • is

  • that

  • which

  • and

  • has

  • have

  • with

  • at

  • of

  • same

  • but

  • does

  • still

  • Also

Postman:

  • Postman is a standalone software testing API (Application Programming Interface) platform to build, test, design, modify, and document APIs. It is a simple Graphic User Interface for sending and viewing HTTP requests and responses.


  • Postman is available as a web application and a desktop client, catering to developers , testers and even non-technical users who work with APIs.


  • Postman supports Javascript as the default language for scripting . But other languages such as Python, Ruby, Java and C# can be used with the help of external libraries and frameworks.

      The main function of Postman:

  • Postman’s  build-in API client allows users to create and send API requests, including HTTP , Graph QL and gRPC requests.


  • APIs work by sharing data between applications, systems, and devices. This happens through a request and response cycle. The request is sent to the API, which retrieves the data and returns it to the user.


Collections in Postman:

Postman collections are groups of saved requests (or) endpoints. Collection is group of different request methods GET,POST,PUT and DELETE.


Send requests in postman to connect to API’s. Requests can retrieve,add,update or delete data and can send parameters and authorization details.


GET: Obtain (or) Get information

POST: Add information (or) Create

PUT & PATCH: Update (or) Replace information

DELETE: Delete information.


Prerequisites: 

  • Create one collection in Postman 

  •   Create one post request


Postman Validations:

 API validation is the process of checking to see if an API meets certain requirements for how it works, how well it performs, how safe it is, and other things. Validation testing, also known as acceptance testing. Validating   actual response and expected response.


To use should and assert assertion styles , you have to create the variables for those. Without creating variables you can’t use should and assert assertion styles in your test. 

To use expect assertion style you no need to create the variable in your test.


Here is the another example for chai assertion styles:




Validation in test:


var jsonData = pm.response.json();

const assert = require('chai').assert

 const should = require('chai').should()


//Test for the response status code

pm.test("Status code is 201", function () {

    pm.response.to.have.status(201);

    });

   

    //If you want to test for the status code being one of a set, include them all in an array and use oneOf

    pm.test("Successful POST request",()=>{

        pm.expect(pm.response.code).to.be.oneOf([200,201]);

    });


//Check the status code text

pm.test("Status code name has string",()=>{

    pm.response.to.have.status("Created");

});

//Check that a response header is present

pm.test("Content-type header is present",()=>{

    pm.response.to.have.header("Content-type");


});

//Test for a response header having a particular value

pm.test("Content-type header is application/json",()=>{

    pm.expect(pm.response.headers.get("Content-type")).to.include("application/json");

});

  //expect

  pm.test("Test data type of the response",()=>{

  pm.expect(jsonData).to.be.an("object");

  pm.expect(jsonData.name).to.be.a("string");

   pm.expect(jsonData.job).to.be.a("string");

   pm.expect(jsonData.name).to.eql("morpheus");

   pm.expect(jsonData.job).to.eql("leader");

   pm.expect(pm.response.id).to.be.a("string");


  });



//should

  pm.test("Response body has expected value", function () {

    pm.response.json().name.should.equal("morpheus");

    pm.response.json().name.should.be.a('string');

    pm.response.json().name.should.not.equal('nothing');


  pm.response.json().job.should.be.a('string');

   pm.response.json().job.should.equal('leader');

  pm.response.json().createdAt.should.be.a('string');

 

 

  });


//assert

  pm.test("Response body has expected value", function () {

     var jsonData1 = pm.response.json();

  assert.isTrue(jsonData1.name === "morpheus", "Name is morpheus ");

  assert.isNotNull('name');

  assert.property(Object,'name');

  assert.lengthOf(Object,1);

  assert.isString('job');

  assert.isNotEmpty(jsonData1.id);

  assert.isNotEmpty(jsonData1.createdAt);

   });



Run the collection to check the validation results:




Conclusion: 

This way you can use any one of the styles of chai assertion (or) all three styles in your test. It helps to validate your actual response and expected response of the request.


Thank you.


151 views
bottom of page