Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React testing library id instead of data-testid?

Would be any difference if I used HTML id attribute instead of data attributes like data-testid?

Reference for the use of data-testid in testing:

https://testing-library.com/docs/queries/bytestid/

like image 578
aldokkani Avatar asked Sep 09 '25 18:09

aldokkani


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

like image 90
Nacho Avatar answered Sep 12 '25 08:09

Nacho


There are at least two reasons to separate the testing ids and the regular ones. You will not feel a difference if these are not of concern to you (and the people who will use and maintain the system).

  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 an id duplication, which in turn has the potential to break the logic of further processing of the page. Nobody loves duplicated ids.

  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 would not clear anything other developers rely on when you keep your testing ids in the regular id field.

like image 33
Sergey Kaunov Avatar answered Sep 12 '25 07:09

Sergey Kaunov