16

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

onuriltan
  • 3,730
  • 4
  • 25
  • 37

2 Answers2

35

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');
Yevhen Laichenkov
  • 7,746
  • 2
  • 27
  • 33
0

What about contains ?

cy.get('.bot-message').contains('I want to send invoice to my email')
wrivas
  • 509
  • 6
  • 12
  • 1
    While `.contains()` works here and implicitly tests this, it is not an assertion which is what the question is looking for. Here's another answer that explains the difference well: https://stackoverflow.com/a/50049358/2883129 – Brendan Jul 25 '19 at 16:16