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(@).
Syntax:
.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.visit('http://zero.webappsecurity.com/login.html')
cy.log('Before Reload')
cy.reload()
cy.log('After Reload')
})
it('Enter signin details',()=>{
cy.get('#user_login').as("username")
cy.get('@username').clear()
cy.get('@username').type('ManThing')
})
it('Enter Password',()=>{
cy.get('#user_password').as('password')
cy.get('@password').clear()
cy.get('@password').type('Shazam')
})
it('Tick checkbox',()=>{
cy.get('input[type="checkbox"]').click()
})
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.visit('http://www.autopract.com/#/home/fashion')
//cy.url().contains('include','home')
cy.get('.close').click()
cy.get('.bar-style').click()
cy.get('#sub-menu').should('be.visible')
cy.get("ul[id='sub-menu'] li[class='ng-star-inserted']").find('a').contains(' clothing ').as('CLOTHING')
cy.get('@CLOTHING').should('be.visible')
})``
})
- 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.