How to use Aliases in Cypress

How to use Aliases in Cypress

Ferenc Almasi β€’ 2021 October 01 β€’ Read time 1 min read
  • twitter
  • facebook

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');
example

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.
});
example

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'));
example

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to use aliases in Cypress?
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.