javascript - 当父元素具有 CSS 属性 : display: none 时, Cypress 如何断言元素可见

标签 javascript css cypress display

如何为父元素隐藏了 css 属性的元素编写 cypress 可见断言? 我有以下 HTMl 代码

<td class="item-total item-total-mobile-hidden">
<p class="mobile-show block-price-text">Total Price:</p>
<span class="price-total">
$699.99
</span>
</td>

当我编写以下 cypress 代码来断言价格元素可见时

Cy.get('.price-total').should('be.visible')

我收到此错误消息 重试超时:预期“”为“可见”

此元素 不可见,因为其父元素 具有 CSS 属性:display: none

我必须尝试在控制台上调试它(将跨度放在变量 $0 中)

$0
<span class=​"price-total">​ $699.99 ​> ​ Cypress.dom.isVisible($0) true

这里显示 span 元素是 isVisible true,但我无法断言它。 我通过调用子元素上的文本尝试了以下操作,但它也不起作用

cy.get('.price-total').invoke('text')
      .then((text)=>{
        const divTxt = text;
expect(divTxt).to.be.visible; })

这没有用,我收到以下错误,因为 Cypress 找不到隐藏的元素 重试超时:预期找到元素:.price-total,但从未找到。

断言元素 可见的最佳方式是什么?

最佳答案

我不确定我是否了解了完整的情况,但是检查 Cypress.dom.isVisible($0) 的技巧不错。

您可以通过使用带回调的 .should() 在测试中使用完全相同的表达式

cy.get('.price-total')
  .should($priceEl => {     // retries if necessary when expect fails

    expect(Cypress.dom.isVisible($priceEl).to.eq(true)

  })

我不确定这是确定的,已经看到一个 Angular 应用程序(选择控件),其中父项是 display: none 但子项对用户可见(引用 Access element whose parent is hidden )

在此答案中,自定义函数用于重新定义可见性标准。诀窍是弄清楚要为您的应用程序检查什么...

// Change this function if other criteria are required.
const isVisible = (elem) => !!( 
  elem.offsetWidth ||                          
  elem.offsetHeight || 
  elem.getClientRects().length 
)

在父元素移除 display: none 之前,您可能只是有一个延迟(例如动画)。

在控制台中检查父级,看看它最终是否有不同的display值。

在那种情况下,首先检查父级(而不是 Manuel 所说的子级)。

cy.get('td.item-total')
  .should('not.have.css', 'display', 'none')  
  .find('.price-total')
  .should($priceEl => {     
    expect(Cypress.dom.isVisible($priceEl).to.eq(true)
  })

关于javascript - 当父元素具有 CSS 属性 : display: none 时, Cypress 如何断言元素可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66646502/

相关文章:

javascript - 当文件缓存在磁盘上时, Cypress 拦截不起作用

javascript - 无法设置 toLocaleString() 的 minimumFractionDigits

javascript - jQuery 分页插件事件目标

css - Bootstrap 3,这是如何指定网格布局的?

javascript - 在 jQuery UI 中堆叠 ListView

css - Webkit Animation 在其下方打破 SVG

javascript - 想要激活当前的 <li>

javascript - 如何在我的客户应用程序中实现桌面通知?

testing - 使用 Cypress 进行 E2E NextJS 测试时如何使用测试数据库?

javascript - 带 Stripe 的柏树 : elements height not loaded