09 Cypress Aliases - biswajitsundara/Cypress GitHub Wiki

Cypress offers a cool feature of aliasing through which we can reuse DOM elements, share context etc.

  • Then command lets us to work with previously yielded subject and it requires to work on that object then and there.
  • But if we want to work with that yielded subject after some time then we need to use aliases.
  • Also we can create aliases and share the context between tests using hooks.
  • We can create alias while dealing with fixtures

Example

Let's say we have a table. Then everytime we don't have to point to the rows, then row. We can use aliases to simplify this.

//This will find all rows of the table
cy.get('table').find('tr').as('rows')

//Using the rows alias, it will click on the first row. 
cy.get('@rows').first().click();

Example

Let's say we have a bunch of menu items, every time we don't have to refer the menu to select the items. We can create alias of the menu items and then select based on our need.

it('Basic Alias Test', () => {
    cy.visit("https://react-redux.realworld.io/#/login?_k=g8c7hl");
    cy.get('ul.navbar-nav').children().as('menu');
    cy.get('@menu').first().click();
    cy.get('@menu').eq(2).click();
 })

Example

Let's say we have to verify something after the then command then we can use alias and after some time with that reference we can verify.

it('Complex Alias Test', () => {
    cy.visit("https://react-redux.realworld.io/#/login?_k=g8c7hl");
    cy.get('ul.navbar-nav').children().first().then(($menuItem) => {
           return $menuItem;
        }).as ("item");

      cy.get('@item').invoke('text').then((text => {
            expect(text.trim()).to.eq('Home');
        }));
  })

Reference

https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-Values

⚠️ **GitHub.com Fallback** ⚠️