How in Cypress, find a card with a specific text and click on a specific button?

everyone!

Faced with a problem, I want to find the card I need in the list of cards guided by the text, and click in this card on the button

The idea is that would not go into details of nesting

Enclosing a screenshot of how it looks like

enter image description here

html structure:

<div class="card">
  <span>name 1</span>
  <button data-test="more-menu"><svg /></button>
</div>
<div class="card">
  <span>name 2</span>
  <button data-test="more-menu"><svg /></button>
</div>
  <span>name 3</span>
  <button data-test="more-menu"><svg /></button>
</div>

Would like something like this

    cy.get('data-test=badge').then(($) => {
      cy.wrap($).contains(`${name} ${lastname}`).then(() => {
        cy.wrap($).find('[data-test=moreMenu]')
      })
    })

>Solution :

You can use the .contains for this. It gets the DOM element containing the text. And then use next() which gets the immediate sibling of the current element, something like this:

cy.contains('span', 'Name 1').next().click()

In case you have a nested structure inside your card class, you can use first parent() which will go to the card parent element and then use within to scope the next commands inside the same card class, something like this:

cy.contains('span', 'Name 1').parent('.card').within(() => {
  cy.get('[data-test="more-menu"]').click()
})

Now We have used parent() once since the .card is available one level up from span. In case you have more levels you have to add more parent().

Leave a Reply