Cypress Create the Aliases before each test

Profile picture for user arilio666

In this article, we will discuss how we can create an alias in before each hook and access them in the test steps.

Before going into the topic, an alias is nothing but a call name for a cypress function using the keyword 'as' to fetch that particular line without any previous code repetition using the alias name.

So, using this name, we can get access to all of the functions it's already doing in other steps.

Syntax for alias

cy.visit('www.autopract.com').as('theSite')
cy.get('@theSite')

Example: Aliases Before Hook

Now, Consider below example where we are using two aliases Popup and sideTab 

describe('Automate AutoPract',()=>{
    before(() => {
        cy.visit('http://www.autopract.com/#/home/fashion')
        cy.get('.close').as('Popup')
        cy.get('.bar-style').as('SideTab')
        
    })
    
    it('Should click POPUP',()=>{
        cy.get('@Popup').click()

    })
    it('Verify Footwear Fashion',()=>{

        cy.get('@SideTab').click()
        cy.get('a').contains(' footwear ').should('be.visible')
    })
    it('Verify Watches Fashion', ()=> {
        cy.get('a').contains(' watches ').should('be.visible')

    })
})


Now, why is that?

  • So in before when we use an alias.
  • It will reset itself after the first test, meaning the same alias will not be available for the 2nd test.
  • So to avoid this problem and use an alias in every test step we will be using before each hook.

Example: Aliases with Before Each Hook

  • We will do the same test steps before each is added to them to avoid the alias being reset.
  • We will be leaving the visit function in before as it is needed only one time.
  • We will be using this hook for repetitive alias usage throughout the test steps.
describe('Automate AutoPract',()=>{
    before(() => {
        cy.visit('http://www.autopract.com/#/home/fashion')
        cy.get('.close').as('Popup')
        
    })
    beforeEach(()=> {
        cy.get('.bar-style').as('SideTab')
        cy.get('a').as('ATag')
    })

    it('Should click POPUP',()=>{
        cy.get('@Popup').click()

    })
    it('Verify Footwear Fashion',()=>{

        cy.get('@SideTab').click()
        
        cy.get('@ATag').contains(' footwear ').should('be.visible')
    })
    it('Verify Watches Fashion', ()=> {
        cy.get('@ATag').contains(' watches ').should('be.visible')

    })
})

  • So from this test, I have also added a part of the selector from footwear and watches test steps as an alias in beforeEach as we will be using the alias in multiple test steps.
  • So to use the alias over the test steps with hooks beforeeach is the right hook to use it across the test steps.
  • So in this way, when compared to normal before hooking, the alias we are setting will not reset after the first test step.