Skip to main content

Cypress Aliases DOM elements

Cypress aliases are an essential feature and have their own uses. To use aliases, we need to invoke/chain the target with .as() which you are gonna share. Imagine a web element with repeated usage. We cant use the selector on every place of the code.
Instead, we use the alias to name that web element line to a custom name which you are gonna use in the code repeatedly.

Then after naming, the alias object can be accessed with a hook(@).


.as('any name')

Let's dive into action on how these work.

Aliasing Elements:

I'm gonna use this in a simple login automation page.

describe('Automating The Signin Of Zero Site',()=> {
    it('visit the site ',()=>{
        cy.log('Before Reload')
        cy.log('After Reload')
    it('Enter signin details',()=>{

    it('Enter Password',()=>{
    it('Tick checkbox',()=>{
    it('click submit button',()=>{
        cy.contains('Sign in').click()
    it('error verify',()=>{
        cy.get('.alert-error').should('be.visible').and('contain','Login and/or password are wrong.')
  • Notice i have used an alias in both the place for username and password selectors.
  • As I need to use them repeatedly, i have implemented this, and the code looks more straightforward and understandable.

Let's see another example.

describe('Automate AutoPract',()=>{
    it('Should load the url ',()=>{
        cy.get("ul[id='sub-menu'] li[class='ng-star-inserted']").find('a').contains(' clothing ').as('CLOTHING')

  • Here I have chained the get, find, and contains and named an alias to them.
  • So similarly, we can use the alias to name repeating future sharable web elements.

Submitted by arilio666 on October 8, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.


At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.