I am trying to do smoke testing by clicking links in a list. After first visit the test stops with following error.
CypressError: cy.click() failed because this element is detached from the DOM.
<a href="/link2">...</a>
Cypress requires elements be attached in the DOM to interact with them.
The previous command that ran was:
> cy.wrap()
What do i do to hold on the element in the loop ?
it('Click each link in the list', () => {
cy.get('li a').each(($el, index, $list) => {
cy.wrap($el).click();
cy.go(-1);
})
})
The objective of the test is to check if all pages in the list come up without 404 errors. Following the html code
<ul>
<li><a href="/link1">Link 1</a></li>
<li><a href="/link2">Link 2</a></li>
<li><a href="/link3">Link 3</a></li>
</ul>
When you invoke cy.get(), you will save the references, and then you navigate away by clicking the link - hence the references to these elements are no longer valid. You could make a list of ids for these elements:
const listOfIds = ['#first_id', '#second_id']
listOfIds.forEach(id => cy.get(id).click())
or if you want to generate your list dynamically, you could do that as well:
function getIds(){
let ids = []
return new Cypress.Promise(resolve => {
cy.get('.your-selector')
.each($el =>
cy.wrap($el)
.invoke('attr', 'id')
.then(id => ids.push(id))
)
.then(() => resolve(ids))
})
}
After that calling getIds().then(ids => ids.forEach(...))
is basically the same as above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With