What is a Cypress Alias?

Rest AssuredDynamic ProgrammingProgramming

Cypress aliases are an important component that has multiple uses. They are listed below −

Sharing Context

We have to use .as() to alias something that we have to share. To alias objects and primitives, Mocha context objects are used. The aliased object can be accessed with - this.*.

Mocha by default shares context for all the hooks applicable for the test and the alias properties are flushed post the execution of a test.

describe('element', () => {
   beforeEach(() => {
      cy.wrap('eleone').as('x')
   })
   context('subelement', () => {
      beforeEach(() => {
         cy.wrap('eletwo').as('y')
      })
      it('aliases properties', function () {
         expect(this.x).to.eq(' eleone ')
         expect(this.y).to.eq(' eleone ')
      })
   })
})
})

We can handle fixtures by sharing context. We can also use cy.get() (asynchronous command) to access an alias with the help of @ symbol(instead of using this.* (synchronous command).

beforeEach(() => {
   // alias fixtures
   cy.fixture('users.json').as('u'})
   it('scenario', function () {
      // '@' to handle aliases
      cy.get('@u').then((u) => {
         // access element argument
         const i = u[0]
         //verification
         cy.get('header').should('contain', u.name)
   })
})

Elements

Alias can be used with DOM elements and later be reused. Here in the below example, by default Cypress makes a reference to td collection obtained as the alias cols. To use the same cols, we have to use cy.get() command.

// alias td in tr
cy.get('tr').find('td').as('cols')
cy.get('@cols').first().click()

As we used @ in cy.get(), Cypress searches for the present alias (cols) and yields its reference.

Routes

Aliases can be utilized with routes. It makes sure that the application has made the requests, awaits response from the server and accesses the request for verification.

cy.intercept('POST', '/users', { id: 54 }).as('u')
cy.get('#btn').click()
cy.wait('@u').then(({ request }) => {
   //assertion
   expect(request.body).to.have.property('name', 'User')
})
cy.contains('User added')

Requests

Aliases can be utilized with requests. We can alias a request and later use its properties.

cy.request('https://jsonplaceholder.cypress.io/comments').as('c')
// other implementations if any
cy.get('@c').should((response) => {
   if (response.status === 404) {
      // assertion
      expect(response).to.have.property('duration')
   } else {
      // do something else
   }
})
})
raja
Updated on 19-Nov-2021 09:39:55

Advertisements