DEV Community

Cover image for How to identify an element by its text with Cypress
Walmyr
Walmyr

Posted on • Edited on

How to identify an element by its text with Cypress

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')
Enter fullscreen mode Exit fullscreen mode

And if we wanted, we could even check that the element is visible, for example.

cy.contains('Any text').should('be.visible')
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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.


Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.

Top comments (0)