如何使用cypress检查身体中是否存在元素?

问题描述

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

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

这有效,但我现在需要 if 块:

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

类似的东西

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

解决方法

如果在这里你不需要任何东西。如果元素不存在,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
    }
  });