网站搜索

reactjs - Cypress 点击时,有没有什么方法可以等待 DOM 加载完成?(不使用 wait())


我在 React 项目中遇到一个小问题,当我想在 Cypress 中使用 .click() 时,有时会出现错误 failed because this element is detached from the dom. 一个简单的解决方法是在每个测试前加上 wait() 以让网站完全渲染,但这对我来说并不是最好的解决方案。有没有不用 wait() 就能解决的方法?

答案#1

这与一个已知的 Cypress 问题有关,他们承诺很快会修复:https://github.com/cypress-io/cypress/issues/7306

在解决那个问题之前,你可以选择添加 .wait(),如果它适用于你的场景,或者替代地尝试 .click({force: true})。不过两者都有缺点。

答案#2

Cypress 文档是你的朋友 =)

我在文档上找到了这个博客。它详细说明了如何使用cypress-pipe在断言之前执行回调函数

// create a click function as pipe does not take any cypress commands
const click = $el => $el.click()

cy.get('.your-element')
  .should('be.visible')
  .pipe(click)
  .should($el => {
    // whatever assertion you need after your click event is attached
  })

// calendar should close on the user click
cy.get('.owl-dt-popup').should('not.be.visible')