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:
Copied to clipboard!
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:
Copied to clipboard! Playground
// β 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:
Copied to clipboard! Playground
// β
οΈ 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:
π More Webtips
Master the Art of Frontend
- Access 100+ interactive lessons
- Unlimited access to hundreds of tutorials
- Prepare for technical interviews