2

I am new to cypress automation. I tried to use the following locator to click on the specific dynamic button.

cy.contains('span', 'Agile Fundamentals').next().find('button').click()

but it did not work.

enter image description here

Fody
  • 23,754
  • 3
  • 20
  • 37
Rock
  • 115
  • 7

3 Answers3

2

.next() won't work in this case because the next element would be the text label with the date.

Instead, we can to use .parent() and .siblings() to move over to the other div and grab that button.

cy.contains('span', 'Agile Fundamentals')
  .parent() // moves us to the div around the span
  .siblings('div') // moves us to the sibling div
  // could use `.next()` above instead
  .find('button') // moves us to the button
  // If you want to save this for ease of use, you can assign it an alias
  .as('dynamicButton')
  // and reference it like...
cy.get('@dynamicButton')...
agoff
  • 5,818
  • 1
  • 7
  • 20
  • Thanks for your super quick response and explaining in detail. Your suggested solution worked :) :) – Rock Jul 11 '22 at 19:50
1

There is another way, change the target of .contains() to the card itself (the top level of that group of elements).

Starting from that element, .find() will get the button regardless of the nesting structure within the card.

cy.contains('div.MuiCardHeader-root', 'Agile Fundamentals')
  .find('button')
  .click()
Fody
  • 23,754
  • 3
  • 20
  • 37
1

Another approach to finding the button would be using the aria-label of the button. This will ONLY work if your DOM does not have another element with the same aria-label value.

cy.get('[aria-label=settings]')
  .click()

If you there are other elements in the DOM that have matching attribute, then you can limit your search to the specific card

cy.contains('.your-card-selector', /agile fundamentals/i)
  .find('[aria-label=settings]')
  .click()
jjhelguero
  • 2,281
  • 5
  • 13