赛普拉斯,获取从 cy.get() 返回的特定元素的索引

Cypress, get the index of a specific element returned from cy.get()

我正在为一个包含一系列引文的网站编写 Cypress 测试,其中一些引文末尾有一个“阅读更多”按钮,该按钮显示引文的其余部分。如果我使用

cy.get(".quote")

它 returns 几个引用的列表。我可以用

cy.get(".quote").find(".read-more").first()

找到第一个带有“阅读更多”按钮的引用,但我想知道该元素在原始引用列表中的索引是什么。我正在测试以确保“阅读更多”按钮正确显示完整引文,但一旦单击该按钮就会消失(完全从 DOM 中删除,而不仅仅是设置为可见性:none),所以我不能使用相同的命令再次找到报价。如果我可以访问该引用的元素,我可以使用

cy.get(".quote").eq(element)

在“阅读更多”按钮消失后再次提取该特定引用。

你可以这样做。在引号上应用 each,然后在每次搜索中搜索您要查找的引号,然后获取该引号的索引。

cy.get('.quote').each(($ele, index) => {
  if ($ele.text().includes('some part of the quote')) {
    cy.log(index) //logs the index
  }
})

阅读更多按钮正确地显示了完整的报价 单击后按钮消失

假设 read more 按钮在被点击后从 quote 元素中删除了 .read-more,那么您可以执行以下操作。

cy.get('.quote') // returns all quotes
  .find('.read-more') // only quotes with 'read more' 
  .each(($quote) => {
       cy.wrap($quote).find('.read-more-button').should('be.visible').click() //check read more button is visible, then click
       cy.wrap($quote).invoke('text').should('include.text',COMPLETE_QUOTE) // you can alter the should to however you best see to the text assertion
       cy.wrap($quote).find('.read-more-button').should('not.exist') // particular read more button does not exist in DOM
})