In today's “Pinches of Cypress”, learn how to identify elements by their text
When creating automated test scripts, we cannot always identify elements by a unique CSS selector.
But what if we could identify them by their text?
I will show you three examples.
In the first example, it doesn't matter what kind of element it is, as long as it has the text that identifies it.
Such an approach is helpful in cases where we know that only one element on the screen will have the text we expect. Otherwise, we run the risk of identifying the wrong element.
The implementation is quite simple.
cy.contains('Any text')
And if we wanted, we could even check that the element is visible, for example.
cy.contains('Any text').should('be.visible')
In the second example, we know that the text will be present in a specific HTML element.
Let's say the element is as follows.
<a href="https://udemy.com/user/walmyr/">Courses</a>
In this case, we want to identify that an anchor element contains the text 'Courses', and that it is visible.
The implementation would be as follows:
cy.get('a:contains(Courses)').should('be.visible')
Unlike the first example, in this case, we use cy.get(). However, instead of passing just a CSS selector, we give a selector together with jQuery's :contains functionality.
And if there is an element of type anchor (<a>) with the text 'Courses', the verification that the element is visible must pass.
In the last example, we'll go back to using cy.contains(), where we'll identify the same element from the previous example and verify that this element is visible.
cy.contains('a', 'Courses').should('be.visible')
As you can see, with cy.contains, we can pass a selector as the first argument and text as the second argument, thus ensuring that the element has the correct text and that the text is contained in the proper element.
That's it!
Did you like it?
I'm looking forward to hearing your feedback!
This post was originally published in Portuguese on the Talking About Testing blog.
Want to go deeper?
I built the Cypress Simulator — a hands-on course designed to take you from your first test to a full end-to-end testing workflow with confidence.
You'll learn how to test real user interactions, catch accessibility issues early, and run your tests automatically in CI/CD pipelines — through 20 interactive lessons, coding challenges, and quizzes.
Top comments (0)