21

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/

aldokkani
  • 853
  • 1
  • 8
  • 17

2 Answers2

29

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

Audwin Oyong
  • 2,247
  • 3
  • 15
  • 32
Nacho
  • 870
  • 6
  • 9
8

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.

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85
Sergey Kaunov
  • 140
  • 1
  • 8
  • _This easily leads to ids duplication_ then it means the same problem for data-testid – aldokkani Sep 30 '22 at 07:59
  • 1
    You're right, but this is how test ids protect you. While they're used only for testing purposes as intended -- only tests could be broken this way, and it won't introduce any worries to production logic. – Sergey Kaunov Oct 01 '22 at 03:30
  • 1
    @aldokkani no, ids do break your app when processing the page, on the other hand data-testid's don't, even if repeated, you'll only get repeated instances of the elements when using getByTestId or query selection, and even then doable, but that's about it – sab Nov 21 '22 at 15:43