首页 > 解决方案 > 如何用柏树检查体内是否存在元素?

问题描述

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

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

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

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

就像是

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

标签: unit-testingintegration-testingcypresse2e-testingend-to-end

解决方案


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

推荐阅读