Did you know about this trick that Cypress contains?

Rester Test
3 min readFeb 8, 2023

There are a lot of videos and articles about Cypress and about tips and tricks in Cypress but the one that this article contains will surely make you say: I did not know that.

When learning an automation tool/framework one of the first actions that we need to master is how to identify the elements on a page.

Contains

The possibily to identify elements based on text was somenthing that is really appreaciated in Cypress and in order to go that you just need to use cy.contains.

However there is one important aspect that you need to keep in mind when using contains. And that is that matching by text can lead to interacting with the wrong element in certain circumstances.

To give you an exampe I will use the below page where I want to view what are the options for my account.

Now If I want to click on the element that contains account the code would look somenthing like this.

it(‘Trick’, () => {

cy.visit(“https://ecommerce-playground.lambdatest.io/index.php?route=account/register")

cy.contains(‘Account’).click({force: true})

})

If we do that then marked element is clicked and we are redirected to the Login page.

So far the contains seem to work fine for us. Now we want to click on My account and then on the Register option to come back to the original page.

Following the same principle as above we should be able to achieve this by using the below code

it(‘Trick’, () => {

cy.visit(“https://ecommerce-playground.lambdatest.io/index.php?route=account/register")

cy.contains(‘Account’).click({force: true})

cy.contains(‘My Account’).click({force: true})

cy.contains(‘Register’).click({force: true})

})

That unfortunately failed because Cypress could not find the element that contains Register.

The reason for that is that the contains command is case sensitive. So it will find one element if you tell it contains(“My Account”) and another one if you tell if contains (“My account”). With this new information we can change the code and retry.

it(‘Trick’, () => {

cy.visit(“https://ecommerce-playground.lambdatest.io/index.php?route=account/register")

cy.contains(‘Account’).click({force: true})

cy.contains(‘My account’).click({force: true})

cy.contains(‘Register’).click({force: true})

})

And as we can see the expected page loads.

Conclusion

For more information about contains and what you can do with it have a look at the official documentation.

Also if you want to see the whole article as a video with a few extras have a look at this video.

https://www.youtube.com/watch?v=nVmyxLmspiA&feature=youtu.be&ab_channel=ResterTest

--

--