Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 489
onuriltan Avatar asked Jul 25 '19 13:07

onuriltan


People also ask

How do you find the element of a class in Cypress?

Get HTML element by Class in Cypress Just like ID, Class is also an attribute of an HTML element, that is used as a locator or selector. Similar to how ID is directly passed with a prefix # using the Cypress command cy. get(), class can also be used to get the HTML element with . (dot) as a prefix inside cy.

How do you use the class element in Cypress?

To select an element by class you need to use . prefix and to select an element by its it, you should prefix id with # . The most common attribute you might find on your page would be a placeholder for an input or even a test-id where your selector starts and ends with square brackets.


1 Answers

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');
like image 195
Yevhen Laichenkov Avatar answered Sep 30 '22 18:09

Yevhen Laichenkov