【问题标题】:How to check if an element exists within the body with cypress?如何用柏树检查体内是否存在元素?
【发布时间】:2021-08-16 19:01:44
【问题描述】:

我想检查一下nextjs-portal标签是否出现在我的页面正文中,如果出现,则点击它。

我怎样才能用柏树做到这一点?

这可行,但我现在需要 if 块:

cy.get('nextjs-portal').click();

类似

if (cy.get('nextjs-portal')) {
  cy.get('nextjs-portal').click();
}

【问题讨论】:

    标签: unit-testing integration-testing cypress e2e-testing end-to-end


    【解决方案1】:

    如果在这里,你不需要任何东西。如果该元素不存在,cy.get('nextjs-portal') 将超时并且不会发生点击。

    如果你真的需要条件测试,可以这样做,但通常是反模式:

    cy
      .get('body')
      .then($body => {
        if ($body.find('.nextjs-portal').length) {
          // now you know the element was found in the DOM
        } else {
          // your element was not found in the DOM
        }
      });
    

    【讨论】:

    • 但是如果元素不存在怎么办?这是一个出现错误的弹出窗口,并不总是存在..
    • 我认为你应该去掉条件测试的需要 (docs.cypress.io/guides/core-concepts/…),然后在你点击这个元素的地方写一个测试。
    • @Codehan25:好的,我更新了我的答案,但我仍然认为通常不需要这样的条件。
    • 现在工作:),谢谢! - 但我也会检查文档:)
    猜你喜欢
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2012-03-18
    相关资源
    最近更新 更多