Skip to content

Instantly share code, notes, and snippets.

@dgowrie
Last active January 28, 2019 18:26
Show Gist options
  • Select an option

  • Save dgowrie/66205f9407a8e70deb54a6b2b876778d to your computer and use it in GitHub Desktop.

Select an option

Save dgowrie/66205f9407a8e70deb54a6b2b876778d to your computer and use it in GitHub Desktop.
UI Tests - resilient selectors

UI testing - use data types for selectors

Add data-testid attributes to elements as dedicated UI test selectors that provide context and are resilient to changes.

--

Reasons data-* type selector are recommended and will help avoid brittle tests:

  • 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

Reasons to prefer data-* type selectors over CSS classnames:

  • 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

Text / content selectors

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.

References:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment