Skip to content

Instantly share code, notes, and snippets.

@thepian
Created December 15, 2014 15:09
Show Gist options
  • Select an option

  • Save thepian/2799b3697c6cb4617d6e to your computer and use it in GitHub Desktop.

Select an option

Save thepian/2799b3697c6cb4617d6e to your computer and use it in GitHub Desktop.
## Writing testable HTML
When you want to test interaction in the UI, you often want to verify the state of a particular element. You might think of adding an id attribute so you can look up the element easily, but that is a bad solution.
The id attribute should only be used for elements that are inherently unique on the page. With changing requirements and future reuse it is hard to say which elements are unique. It also limits testing in parallel. If for instance a test runner renders a component multiple times without cleaning up the DOM to run the fastest, the test might not be working on the right element as 'getElementById' will not complain about multiple elements with the same id, it is also not defined which one it will get. Usually it is the first matching in the s a rule of thumb you should never use the id attribute outside pages served by the server; Never in views and templates.
To make an element easy to fetch in a test, put a unique attribute on it, and use CSS or xpath selector to match it. Be careful that you are testing the actual requirement, not the presence of an element circumstantial to the requirement.
For instance you can add an attribute to a div, `<div data-test-customer-address>...</div>`. You can now locate the address with the selector `[data-test-customer-address]`.
Consider carefully if you need special attributes for test identification at all. The most common test is relating to forms or form elements. In Angular and standard HTML these have name attributes that are unique within the context. You should be able to make assertions about the fields of the general form by looking up `form[name=general]`. In there you can assert that an element contains a certain text string, or that a select has a number of options.
Also consider that the OOCSS principles lead to CSS classes being applied that are both general and specific to key elements. You can use the specific class to assert the existence of the exact element you are looking for. You can use the general classes to assert visual semantics intended.
* Be specific in locating the particular named form or OOCSS class in the page
* Add testing attributes only if there is no other need for the application to identify an element
* Make fuzzy assertions about the contents of the located element.
These principles will allow for the most painless future refactoring.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment