Get multiple aliases at once without callbacks in Cypress

Aliases are a powerful feature in Cypress that allows you to create references to elements on a web page and use them in subsequent commands. However, it can be tedious to get multiple aliases one by one, especially if you need to reference a large number of elements. See how to write a command to get many aliases at once.

March 12, 2023 cypress

Problem

Cypress does not provide a method to compare aliases or to get many aliases at once. Because of that to compare aliases you have to get each alias individually, creating a callback hell.

1
cy.get("#birthday").as("birthday");
2
cy.get("#age").as("age");
3
4
// ugly
5
cy.get("@birthday").then((birthday) => {
6
cy.get("@age").then((age) => {
7
expect(birthday).to.eq(age);
8
});
9
});

To get a deal with it we are going to create a new command called getMany which will take array with any kind of selectors (like aliases, elements etc).

1
cy.get("#birthday").as("birthday");
2
cy.get("#age").as("age");
3
4
cy.getMany(["@birthday", "@age"]).then(([birthday, age]) => {
5
expect(birthday).to.eq(age);
6
});

Adding custom command

To resolve the described problem we can add a new command to Cypress’s commands called getMany. Thanks to this we can get as many aliases or elements as we want. To use this command copy-paste the implementation to cypress/support/commands.ts.

1
Cypress.Commands.add("getMany", (names: string[]): Cypress.Chainable<any[]> => {
2
const values: any[] = [];
3
4
for (const arg of names) {
5
cy.get(arg).then((value) => values.push(value));
6
}
7
8
return cy.wrap(values);
9
});

Adding type signature of the custom command

To let TypeScript‘s compiler knows that we have added a custom command and have IntelliSense working, we have to describe the type signature of the custom command in the file cypress/support/index.d.ts. The type signatures should match the arguments custom commands expect. Here is how this file looks:

1
declare namespace Cypress {
2
interface Chainable<Subject = any> {
3
getMany(names: string[]): Chainable<any[]>;
4
}
5
}

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment