How to use Aliases in Cypress
Want to reuse the same selector over and over again in your Cypress test? You likely want to use an alias for that to only query it once using the as
command:
cy.get('.banner').as('banner');
// This will yield the β.bannerβ element
cy.get('@banner');
You can access aliases in your test cases using the @
prefix. Note however, that aliases are cleared after each test, therefore the following will not work:
// β Aliases are cleared after each test
it('Works here', () => {
cy.get('.banner').as('banner');
cy.get('@banner');
});
it('Doesnβt work here', () => {
cy.get('@banner'); // could not find a registered alias for: @banner.
});
Instead, if you need to reference the same alias in multiple places, you can set it up using a beforeEach
hook to set up the alias prior to running every test case:
// β
οΈ Use beforeEach to make it work
beforeEach(() => cy.get('.banner').as('banner'));
it('Works here', () => cy.get('@banner'));
it('Works here as well', () => cy.get('@banner'));
it('And for every test', () => cy.get('@banner'));
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: