Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find multiple elements within certain element in Cypress

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:

  1. 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-')]) ?

  2. 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.

like image 571
user8828251 Avatar asked Nov 25 '25 13:11

user8828251


1 Answers

  1. 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 (e.g. data-testid='option'), and another one that holds the interesting value (e.g. data-value='1')

  1. The cypress-xpath extension is the only way I know of to use xpath with Cypress. Regarding performance I don't have any data. I believe that it's slower then 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.
like image 90
Arnon Axelrod Avatar answered Nov 27 '25 01:11

Arnon Axelrod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!