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)
?
CodePudding user response:
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');
CodePudding user response:
You can create a custom command for this. Go to cypress/support/commands.js
and write:
Cypress.Commands.add('selectElement', (index) => {
cy.get('selector').find('selector').eq(index).should('be.visible')
})
And then in your test just write:
cy.selectElement(1)
cy.selectElement(2)