DEV Community

Cover image for Cypress selector trick
isolderea
isolderea

Posted on

Cypress selector trick

As you might know when dealing with the topic of selector there is Cypress recommendation to use data-testid. Best Practice

Image description

However in order to get those data-testid you will need to talk to the frontend team and have them add it to the DOM as part of one of their task. But is there a way to still make yourtests while you wait for the ids to be implemented?

The answer is YES

So let us explore the solution step by step.

The initial situation

We have a simple test that navigates to this website, fills in a few fields, submit a form and check for an error message.

The Cypress code looks as below and as you can see we have a really nice scenario where for almost all elements we have unique ids.

Image description

However we want to use data-testids in the code but without making the test fail while we wait.

The solution while you wait

The way we can achieve our goal is by using a not so know feature of cy.get.

We are allowed to provide cy.get with more than one locator as long as we respect the format. So we can enter in the code a placeholder for data-testid and the current working locator. See the below example

cy.get(‘[data-testid=””],#name’).type(‘test1’);

After having done all the changes you can run your tests and the test will pass with no issues since it will be able to find the element you want by using the original id.

Image description

Final code
Once you have the new data-testids in your DOM you can bring the code to its final form.

Image description
And if we run the test we can see it passes.

Image description

Conclusion

Give this solution a try and write what you think about it. Are there other scenarions where you might consider using it?

Top comments (0)