Code:
<div class="title">
<button data-testid="tg-menu" class="hitbox-border">
<img src="asldij">
</button>
<div class="menu" data-testid="menu-list">
<button class="text-left" data-testid="option-1">
<span>Menu Option 1</span>
</button>
<button class="text-left" data-testid="option-2">
<span>Menu Option 2</span>
</button>
<div class="row">
<div class="flex-grow">
<hr class="lightgrey-border">
</div>
<div class="flex-grow">
<hr class="lightgrey-border">
</div>
</div>
<button class="text-left" data-testid="option-3">
<span>Menu Option 3</span>
</button>
</div>
</div>
Tool: Cypress
I have code similar to above and want to do couple of things easily without using -- Class Names when selecting elements.
I can do it as cy.get('[data-testid="menu-list"]').children('button') but wanted to get it similar to xpath - contains...as above example is simple but some of the things are more difficult in dom.
Questions:
Find All the Button Names under menu list.
Is there one line cy.get() I can use similar to By.xpath( //div[@data-testid='menu-list']//button[contains(@data-testid,'option-')]
)?
Is there easy way to translate selenium xpath to cypress...
Note: I know there is extension for xpath for cypress not sure if performance wise it is good or not.
AFAIK it's not possible to use something like contains
in a css selector (which is what cy.get
is using). However, your can get all the buttons and invoke each
on them to get the value of data-testid
For example:
cy.get('[data-testid="menu-list"]').children('button').each(btn => cy.log(btn.getAttribute("data-testid")))
In case you have buttons that their data-testid
attribute does not start with option-
and you want to filter them out, I'd suggest to have 2 different data attributes: one for the filtering which is doesn't have to be unique (eg data-testid='option'
), and another one that holds the interesting value (eg data-value='1'
)
cy.get
with css selector, just like it's in Selenium. But I also believe that in most cases it's pretty meaningless. As with any performance question, the best answer is to perform your own measurements in the context that's relevant to you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.