Cypress selector trick

Rester Test
3 min readApr 1, 2024

--

As you might know when dealing with the topic of selector there is Cypress recommendation to use data-testid. https://docs.cypress.io/guides/references/best-practices

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.

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.

Final code

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

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

Conclusion

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

--

--