Cypress – Aliases

Cypress aliases are an important component that has multiple uses. These uses 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(), which is an asynchronous command, to access an alias with the help of @ symbol (instead of using this.*) This is the 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

An alias can be used with Document Object Model (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. Then, it awaits a 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. This can be done as follows −

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
      }
   })
})

Leave a Reply