Add data-testid attributes to elements as dedicated UI test selectors that provide context and are resilient to changes.
--
-
Targeted
data-*type selector creates explicit relationship between test and source code -
Dedicated
data-*attribute is easy to reason about, unambiguously used as test selector only -
Well-named
data-*attribute provides clear context in the test -
data-*attributes insulate tests against CSS or content changes
-
CSS classnames in general are expected to be for styling only
-
Mixed use of CSS classnames as test selectors adds ambiguity (what's it do? can it be safely removed?)
-
Sass / BEM-based CSS selectors will be phased out in favor of CSS-in-JS (emotion)
-
Generated CSS classnames are non-deterministic, random strings which provide no context
Main argument against using inner text / content as a selector is this content is mutable, thus brittle. Exception would be if the UI test specifically is meant to ensure that content has not changed, in which case targeting by content selector is appropriate, i.e. if the content changed / is not found, the expected result is a failed test.