API Testing with cypress

API Testing with Cypress

Cypress is an end to end testing framework that is catching up among the QA community as a GOTO choice automation framework. In this blog post I will give a quick introduction into how API testing can be done with cypress.

Let's say we have an API that returns the result of a list of doctor names. To retrieve the list of results requires two step process. In step 1, we need to make a POST request call an authorization server and get a jwt-token and in the second step we use the jwt-token to make a GET call.

With cypress the API request are performed using the cy.request method and cypress assumes that the default API call is a GET. When we make an API  request with cypress, it uses Node.js as an engine to make the HTTP requests to the API server.

There are 4 main sections of the API request that we write within the cy.request they are :

  • method : if its a GET/POST/PUT or DELETE
  • url: the endpoint we want to call
  • header: the header parameters ex:content-type, authorization bearer
  • body: the request payload
describe("api testing with cypress", () => {

it("invoke the API call", () => {

 cy.request({

        method:'POST',

        url:'http://localhost:9090/authorization-server/authenticate',

        headers:{

          'Content-Type': 'application/json',

          'Accept': 'application/json',

          'Accept-Encoding':'gzip, deflate, br'

        },

        body: {

            "deviceType": "WEB",

            "username" : "admin",

            "password" : "admin@123"

        }

   }).then((res)=>{

    jwtTokenVal=res.body.jwtToken

   })

   

The below example shows the use of the jwt-token we obtained from step 1 to invoke a GET call to obtain the list of doctors

  cy.request({

            method:'GET',

            url:'http://localhost:9090/usermgt-service/api/v1/doctors?pageNo=1&pageSize=8',

            headers:{

                  'Content-Type': 'application/json',

                  'Accept': 'application/json',

                  'Accept-Encoding':'gzip, deflate, br',

                  'Authorization': 'Bearer ' +jwtTokenVal

            }

        }).then((resp2) => {

       expect(resp2.status).to.eq(200)

       expect(resp2.body.page[0].doctorId).to.be.not.null;

        })

 })

 })

As with any test, we need to write our assertions to validate that the response returned from the GET call is what we expected. For this we use the Chai, BDD assertions "expect(resp2.body.page[0].doctorId).to.be.not.null;" to validate the response we have received.

To make our code more readable we can put the POST request to obtain the jwt-token within a beforeEach() and put the GET  request inside the it() block. And finally, when the test are run, the results can be seen on the cypress test runner.




   

Comments