首页 > 解决方案 > 使用 Cypress 进行探索性测试时如何处理分离的元素?

问题描述

我已经制作了一个赛普拉斯脚本来测试一个大型站点“探索性”,这意味着它将解析所有链接和元素并与它们进行交互,以寻找意外的 JavaScript 或服务器异常(旁注:我不能在网上找到这样的例子?)。它像疯了一样地遍历整个站点,效果很好。然而,有时测试会停止在可怕的“CypressError: cy.click() failed because this element is detached from the DOM”上。

Cypress requires elements be attached in the DOM to interact with them.

The previous command that ran was:

  cy.wrap()

This DOM element likely became detached somewhere between the previous and current command.

我知道这是因为脚本正在与页面动画和切换状态进行交互,并且脚本可以跳过所有这些分离的元素并继续运行,但是我无法设法忽略错误。您会认为检查 Cypress-dom-helpers 就足够了,但他们似乎没有完成这项工作(见下文)。我尝试为 cy.wait() 使用更大的值,但由于某种原因,即使上次交互的所有页面操作都已完成,它仍然无法捕获分离的元素。

请注意,wrap作品,但不是点击。

        if (Cypress.dom.isVisible(element[0]) && !Cypress.dom.isDetached(element[0])) {
            cy.wrap(element[0])
                // .scrollIntoView()
                .click({ force: true })
                .then(() => cy.wait(100));
        }

我不想吞下所有意想不到的错误,因为它们可能很有意义......这里的想法已经用完了。


编辑

这是导致 cy.wrap() 的更多代码。如您所见,仅捕获明显的 javascript 和服务器错误是非常初级的:

clickAllElements = () => {
    this.getAllClickableElements().each(this.clickElement); //running it twice to toggle state
    this.getAllClickableElements().each(this.clickElement);
};

getClickableElementsSelector = () => "button:visible, a:visible[href='javascript:;'], a:visible[href='#'], a:visible[href='javascript:void(null)'], a:not([href])";
getAllClickableElements = () => cy.get(this.getClickableElementsSelector()).not(".disabled");

clickElement = (element) => {
    if (Cypress.dom.isVisible(element[0]) && !Cypress.dom.isDetached(element[0])) {
        this.checkMainError();

        cy.wrap(element[0]) // i tried cy.get here as well to re-get the element, but with the same detached error on click
            // .scrollIntoView() //ideally i'd like to have scrollIntoView here as well, but that won't work with hidden elements (as click({force}) does)
            .click({ force: true })
            .then(() => cy.wait(100));
    }
}

这是跑步者的屏幕截图,尝试使用 cy.get 而不是 cy.wrap。cy.wrap 的结果是相同的:赛普拉斯赛跑者

标签: javascriptautomated-testsintegration-testingcypress

解决方案


推荐阅读