javascripthtmlreactjstestingautomated-tests

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/


Solution

  • 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.