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.
And if we wanted, we could even check that the element is visible, for example.
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.
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:
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.
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.
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.