Cypress.io quick tip: Put elements in the context

furbo
code.kiwi.com
Published in
3 min readMar 11, 2021

Let’s take a page with multiple elements that have the same unique attribute and you want to interact with each of them separately.

In our case, we want to book a flight for a family of three passengers — male, female, and an infant, so we need to fill in three forms.

The form is originally taken from the passenger info step at Kiwi.com but simplified for presentation purposes.

Looking at the HTML structure, each form is wrapped in a divelement with adata-test attribute. Although we are following the best practices, this might be an issue.

💣 Problem

If we want to fill in the first name for each passenger, we will use the following code.

The cy.get('[data-test=ReservationPassanger]') will yield all elements that match the given selector. By providing the index in the eq() method, we are picking the element from the list.

We rely only on the index of the element, and this approach can lead in the long term to less readable and low maintainable code.

Can we do better? Yes, we can.

💡Solution

1. Give our elements context

As we know that the cy.get('[datatest=ReservationPassanger]') yields a list of three elements, we can provide an alias to each element of the list using the as() method.

Instead of relying on the index of the elements throughout the whole test, we can now get the desired form by its @alias name.

Since we have three forms on the page, we named each of them by the passenger.

You can find fully working code at the end of the article. 👨 👩 👶

2. Frame the interaction

From this point, we can handle our interaction with each form individually. We can get the desired form using cy.get('@{alias}') and use the method within() to frame our interaction only to the selected form and isolate the rest of the page.

The result is highly readable and easily maintainable code.

You can find fully working code at the end of the article.

☝️Takeaway

If you have multiple elements with the same locator, you don’t need to rely on the index of the element on the page. By providing an alias, you can set the context to the element and use it in your test to better understand your code without unnecessary comments.

💾 Code

Join us

Searching for a new adventure in Engineering? Check our open positions.

Happy testing 🚀

--

--

furbo
code.kiwi.com

Call me Furbo. I enjoy testing, test automation, teaching and buliding LEGO.