Pretty new to cypress (12.16) here and have a question:
I have a form that gets used in multiple areas of the app, I’m trying to turn filling it out into a command to centralize it in case we need to change variables, the issue is that I need to select an element which has an ID that can be either ‘UI-1’ or ‘UI-2’, and my JavaScript isn’t great – I’m wondering if there’s a way to build a selector that essentially looks for ‘UI-1’ and if it doesn’t find it then look for ‘UI-2’ and continue.
2
Answers
Cypress selectors use jQuery syntax. You can pass multiple selectors to
cy.get
by separating them with commas. For example, here’s how to select elements withid="UI-1"
orid="UI-2"
:You can take the approach of partial attributes, since
id="UI-1"
is an attribute you are not limited to using#UI-1
.You can also use
[id="UI-1"]
and there are variations one of which is startsWith[id^="UI-"]
which will find anyid
starting withUI-
.See this page for a complete list jQuery Attribute selectors
If you pick up multiple elements, just apply
.first()
command before.type()
, or if you want to type into all of them use.each()
As for a custom command, it’s pretty simple
You can put it into the support folder to centralize the code (although I wouldn’t bother with that, since global searching is pretty easy when you need to update the selector).