onuriltan
onuriltan

Reputation: 3908

How to get 2nd div of the same class with Cypress

I have a chatbot application which I want to test it with Cypress. I'm looking at the case if the bot has responded to client correctly. So I check after click I should get a div which has class bot-message.

cy.get('.bot-message').should('have.text','I want to send invoice to my email')
CypressError: Timed out retrying: expected
[ <div.bot-message>, 3 more... ] to have text 
I want to send invoice to my email. , but the text was 
I want to see my profile.I want to see my invoices.
I want to send invoice to my email

The problem here is that cypress gets all the divs within a class named bot-message.

So what I want to be able to do is to say get the 3rd div of the same class. If that is not the case then I think I should give data attributes to every bot message div

Upvotes: 17

Views: 27322

Answers (2)

wrivas
wrivas

Reputation: 509

What about contains ?

cy.get('.bot-message').contains('I want to send invoice to my email')

Upvotes: 0

Yevhen Laichenkov
Yevhen Laichenkov

Reputation: 8672

Use the eq to get A DOM element at a specific index in an array of elements.

From API docs:

The querying behavior of this command matches exactly how .eq() works in jQuery. Its behavior is also similar to that of the CSS pseudo-class :nth-child() selector.

cy.get('.bot-message')
  .eq(1) // to get 2nd element. array index (counting) starts from 0
  .should('have.text','I want to send invoice to my email');

Upvotes: 38

Related Questions