CSS is meant to style your elements. Sometimes you do that via class and sometimes there is elements that want to be styled the same way all the time e.g. h1
.
In my past experience I have seen a lot of projects that write their tests depending on css classes. Although this works it is architecturally not the finest of the finest.
Let's face following problem:
<article class="article">
<strong class="article__title">Whatever</strong>
<p>Some text</p>
</article>
Now your task is to test if the "Whatever"
is contained.
In your tests you might be doing something like on of these options:
// Option 1:
expect(...query('strong').innerText.trim()).toBe('Whatever');
// Option 2
expect(...query('.article__title').innerText.trim()).toBe('Whatever');
The first option is probably the worst since it means that changing the strong
to e.g. em
or h2
you would need to adapt that in the test as well.
The second option with querying article__title
class is more stable. But also only if you are using this exact semantical BEM approach. If you use something like Tailwind or bootstrap are you then going to search for whatever-xl-highlight
class?
⚡️ Both options are not stable for changes!
The stable option is to add semantic probe
identifiers.
<article data-probe-id="blogpost">
<strong data-probe-id="blogpost__title">
Now whatever changes stylewise, removing classes, adding classes, changing class names, the probe-id
will stay and make the life of your Teast team easier as it rarely needs to adapt.
Also what comes in handy in Test-Driven-Development is that the Test Team can define the probe-id
values upfront before implementation.
Problem solved 🚀
Top comments (2)
Except that's not valid HTML,. You should use
data-probe-id
instead.Thanks for the comment. In our company we do use
data-probe-id
. However even though that is true in actual HTML context it really rarely ever comes with business related downsides not doing so.If you are all about validity for a specific reason then you could redefine your own doctype :)