Im quite new with Cypress, and have been having some great luck with the library. But find myself stuck on this specific situation.
I am stuck on a selecting a button on a specific div that contains specific text. I need to click on a button depending on what the sibling divs contain.
Our layout looks something like this:
<div class="MuiList-root">
<div class="MuiListItem-root">
<div class="MuiListItemText-root">
Whatever 1
</div>
<div class="MuiListItemIcon-root">
<button type="button" onClick={()=>{...}}>Delete</button
</div>
</div>
<div class="MuiListItem-root">
<div class="MuiListItemText-root">
Delete This One
</div>
<div class="MuiListItemIcon-root">
<button type="button" onClick={()=>{...}}>Delete</button
</div>
</div>
<div class="MuiListItem-root">
<div class="MuiListItemText-root">
Whatever 2
</div>
<div class="MuiListItemIcon-root">
<button type="button" onClick={()=>{...}}>Delete</button
</div>
</div>
</div>
The goal is the click the "Delete" button on the ".MuiListItem-root" that contains "Delete This One". The list is dynamic, so Im unable to use the position of the item.
** Hacky Solution that works - There has to be a better way **
// Clicks the edit button - There has to be a better way of clicking the elements delete button.
cy.get("[id='stuff'] .MuiTypography-displayBlock").then((elements)=>{
Object.keys(elements).forEach((item,index)=>{
let classificationIndex
if(elements[item].textContent === `Delete This One`) {
classificationIndex = index
cy.get("[type='button']").eq(classificationIndex).click()
}
})
})
I get a little more specific, then find the index of the element that reads "Delete This One". Once I know the index, i then grab the buttons and click on the "Delete" of that specific index.
There's a couple of ways to do this. As your description says, go to the .MuiListItemText-root
and find it's sibling,
cy.contains('.MuiListItemText-root', 'Delete This One') // get the div with the text
.siblings() // get sibling elements
.eq(0) // take the first (and only)
.find('button') // find button within
.click()
but .contains()
also finds text within descendants so you can target the MuiListItem directly and save some steps
cy.contains('.MuiListItem-root', 'Delete This One') // get grandparent of text
.find('button') // find button within
.click()
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.