'Cypress iterating through elements to click on, bad practice?
In my scenario, I am clicking on a dropdown selection, which yields the child elements to be clicked on. I am wanting to click on the first element/option, here's my approach which is working.
cy.get( 'ul[role="listbox"]' ).children().each(( $btn, index ) => {
// clicks first option in dropdown
if( index === 0 ) {
cy.get( $btn ).click();
}
});
The reason I'm doing it like this, is when I try to click directly on the element without iterating through the children, I'll sometimes get the error "cy.click()` failed because this element is detached from the DOM."
But the way I have it implemented now, the error does not occur.
HTML for the dropdown (has 2 options in this case, can be any amount):
<div role="listbox" class="hd">
<ul role="listbox" tabindex="0" data-baseweb="menu" id="bui-3" aria-multiselectable="false" class="dc au b4 b3 b5 ba he hf ay az dd de df dg h8 cv dr hg">
<li role="option" aria-disabled="false" aria-selected="false" id="bui-5" class="ae e2 ag ga au e5 hl e9 ao hi ei d7 b3 he hf hj hk dr">
<div aria-selected="false" class="e9 ag">Dropdown Option 1 </div>
</li>
<li role="option" aria-disabled="false" aria-selected="false" id="bui-6" class="ae e2 ag ga au e5 hl e9 ao hi ei d7 b3 he hf hj hk dr">
<div aria-selected="false" class="e9 ag">Dropdown Option 2 </div>
</li>
</ul>
</div>
Solution 1:[1]
Have you tried finding the first li, using Cypress' .find() command? I would guess that this would work and hopefully not give you the error message described.
cy.get( 'ul[role="listbox"]' )
.find('li') // searches for all `li` underneath the yielded element
.eq(0) // selects the item at the index
.click();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | agoff |
