Search code examples
testingselectcypressdry

How could I do not repeat the selection process in Cypress?


How could I do not repeat the selection process in Cypress?

E.g. if I have:

cy
   .get("...").find("...")...eq(0)...should("...")
   .get("...").find("...")...eq(1)...should("...");

How could I avoid duplicating the .get("...").find("...")... part if at some point I need to pick either the eq(0) or the eq(1)?


Solution

  • You can use .as() to alias an element.

    // Just aliasing the base
    cy.get('foo').find('bar').as('something');
    cy.get('@something').eq(0).should('exist');
    cy.get('@something').eq(1).should('exist');
    
    // aliasing the specific elements
    cy.get('foo').find('bar').eq(0).as('firstEl');
    cy.get('@firstEl').should('exist');
    cy.get('foo').find('bar').eq(1).as('secondEl');
    cy.get('@secondEl').should('exist');
    

    You could also use a custom command.

    // If the selectors in `get` and `find` are constant, you could do a custom command
    Cypress.Commands.add('myGet', (index) => {
      return cy.get('foo').find('bar').eq(index);
    })
    cy.myGet(0).should('exist');
    
    // Or if you wanted to be able to customize the get and find
    Cypress.Commands.add('myGet', (get, find, index) => {
      return cy.get(get).find(find).eq(index);
    })
    
    cy.myGet('foo', 'bar', 0).should('exist');