使用Cypress.each遍历链接访问页面时断言失败,提示DOM元素脱离
问题描述
使用Cypress 10.7.0编写E2E测试时,遍历表格内多个链接并跳转页面后执行断言,出现以下报错:
Timed out retrying after 4000ms: cy.should() failed because this element is detached from the DOM. <div id="content" class="css-1ddoub">...</div> Cypress requires elements be attached in the DOM to interact with them. The previous command that ran was: > cy.wait() This DOM element likely became detached somewhere between the previous and current command.
测试代码如下:
cy.get('[id="content"').parent().within(()=>{ cy.get('[data-cy="list-item"]').each(item => { const link = item.find('a').first(); cy.visit(link.attr('href')!) cy.wait(5000) cy.findByText(/report herunterladen/i) }) })
注意:硬编码URL直接访问时,所有断言正常工作:
cy.visit('/de/banks/compare/?a=calculations.average&b=ins.PL.PKO') // Hardcoded url cy.wait(1000) cy.findByText(/report herunterladen/i)
已尝试延长cy.wait()至30000ms,问题仍未解决。
问题原因与解决方法
核心原因
并非cy.each()存在bug,而是回调函数中保留了对原页面DOM元素(item和link)的引用。执行cy.visit()跳转页面后,原页面的DOM会被完全销毁,但Cypress的命令队列仍试图关联之前的DOM上下文,最终触发"元素脱离DOM"的报错。
解决步骤
- 先提取所有链接的href到数组,再遍历数组访问
脱离原DOM元素的引用,避免上下文冲突:// 修正语法错误:补全content选择器的闭合引号 cy.get('[id="content"]').parent() .find('[data-cy="list-item"] a:first') .then($links => { // 将jQuery对象转为普通数组,提取所有href属性 const hrefs = Array.from($links).map(link => link.getAttribute('href')) // 遍历href数组执行测试 hrefs.forEach(href => { cy.visit(href) // 用断言替代固定等待,让Cypress自动等待元素加载 cy.findByText(/report herunterladen/i).should('be.visible') }) }) - 移除固定
cy.wait(),改用基于元素的断言
Cypress是异步驱动的,固定等待时间不可靠,应通过断言让Cypress自动等待目标元素出现并可见。 - 修正语法错误
原代码中cy.get('[id="content"')缺少闭合引号,会导致选择器异常,需补全为cy.get('[id="content"]')。
内容的提问来源于stack exchange,提问作者Phaki
相关产品推荐
相关产品推荐

