Cypress Aliases Requests

Profile picture for user arilio666

So we know aliasing the dom elements in cypress is easy and very convenient.
So what if when you are doing API testing in cypress and need to use aliasing in there as well?

In cypress, we can use aliasing in requests as well as it is very convenient to be used up in the late part of the code by calling the alias name.

We will be making a GET request in this article, for example, purpose in a site called httpbin.org.
The same what I'm about to do will work for all the HTTP methods as well.

Syntax for alias:

.as('name of your choice')

cy.get('@name of your choice')

Example:

describe('Testing out request in cypress',()=>{
    it('Visiting the api test site httpbin',()=>{
        cy.visit('https://httpbin.org')
    })
    it('GET',()=>{
        cy.request({
            method : 'GET',
            url : 'http://httpbin.org/get'

        }).as('GETreq')
        cy.get('@GETreq').then((Response) => {
            expect(Response.body).have.property('origin')

        })
    })
})
  • So here we are doing a simple GET method as request.
  • We are going to the respective site by cypress visit command.
  • Then in the next test step, we are doing the request command and wanting to make a GET request from the URL with the get endpoint.
  • So we are aliasing that whole part with .as in the end and naming it GETreq.
  • In the following line, we are fetching the alias with get, using the then command to assert the response.
  • We are asserting the response to expect the body of the response to have a property from the get endpoint.

Endpoint:

{
  "args": {}, 
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", 
    "Accept-Encoding": "gzip, deflate", 
    "Accept-Language": "en-US,en;q=0.9", 
    "Host": "httpbin.org", 
    "Upgrade-Insecure-Requests": "1", 
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38", 
    "X-Amzn-Trace-Id": "Root=1-61668208-498c783d073813f76ecf588e"
  }, 
  "origin": "27.5.123.114", 
  "url": "http://httpbin.org/get"
}

As you can see, I'm asserting for the origin property to be present there as it is there.

Output:

So as we can see, the test has passed and successfully verified that it has the property called origin from the get endpoint.