DEV Community

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

Posted on • Updated 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 two 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 useful when we know that only one element on the screen will have the text we expect.

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 one, we use cy.get(); however, instead of passing just a CSS selector, we pass a selector together with :contains(Courses).

And if there is an element of type anchor (<a>) with the text 'Courses', the verification that the element is visible must pass.

That was 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.

Discussion (0)