React testing library id instead of data-testid?

Viewed 14947
2 Answers

On the surface, I don't see any technical difference.

But in terms of readability, data-testid may notice other developers that this is used for test case specifically, while id is may be in terms of styling.

Also id or class selectors can be changed more often if implementation changes.

Reference:

Making your UI tests resilient to change

There are at least two reasons to differentiate testing ids and regular ones. If both of them are not concerned for you (and the people who will use and maintain the project), then you will feel no difference.

  1. Components reuse

React Components reuse is one of the core concepts of the framework. And in general, components can appear several times in one page/view. This easily leads to ids duplication, which in turn has the potential to break the logic of further processing of the page. Nobody loves duplicated id.

  1. Cleaning the code for production

It's straightforward to employ any method of getting rid of data-testid attribute before publishing your package. But it's hard to be sure you don't clear anything other developers rely on when you keep your testing ids in the regular id field.

Related