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
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With