0

I'm writing Cypress tests for a website that has a series of quotations, some of which have a "Read More" button at the end, which displays the rest of the quote. If I use

cy.get(".quote")

it returns a list of several quotes. I can use

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

to find the first quote that has a Read More button, but I want to know what the index of that element is in the original list of quotes. I'm testing to make sure that the Read More button correctly reveals the full quote, but the button disappears (entirely removed from the DOM, not just set to visibility: none) once it's been clicked, so I can't use the same command to find the quote again. If I could access the element of that quote, I could just use

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

to pull out that specific quote again once the Read More button is gone.

Josh Halpern
  • 13
  • 1
  • 3

3 Answers3

4

You can do something like this. Apply each over the quotes, then inside each search for the quote you are looking for and then get the index of that quote.

cy.get('.quote').each(($ele, index) => {
  if ($ele.text().includes('some part of the quote')) {
    cy.log(index) //logs the index
  }
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • This is great but I'm still stuggling to actually return that index value. I'm trying to create a function that will return an index not just log it. Its hard to get my head around these magical promise like not quite async functions. – rod howard Mar 16 '23 at 22:54
0

Read More button correctly reveals the full quote then button disappears once clicked

Assuming the read more button removes the .read-more from the quote element after being clicked, then you can do the following.

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
})
jjhelguero
  • 2,281
  • 5
  • 13
0

If you want to make a common function for this, the only way I've been able to get the index in this case is by doing the following:

const indexes = []
cy.get('.quote').each(($ele, index) => {
  if ($ele.text().includes('some part of the quote')) {
    indexes.push(index)
  }
})
return indexes

Then if you're expecting it appear just once, just get the first index out of the array.

Mark
  • 136
  • 9