nhsbsa / nhsbsa-digital-playbook

Defines how the NHS Business Services Authority provides digital services
https://nhsbsa.github.io/nhsbsa-digital-playbook/
Apache License 2.0
8 stars 4 forks source link

Coding frontend - general guidance - ID's #207

Open jamessan85 opened 1 year ago

jamessan85 commented 1 year ago

What

Change using ID's to target fields for functional testing and use data-* instead. ID's can change.

Why

Although we may not use Cypress, general guidance is write selectors that are resilient to change.


Every test you write will include selectors for elements. To save yourself a lot of headaches, you should write selectors that are resilient to changes.

Oftentimes we see users run into problems targeting their elements because:

Your application may use dynamic classes or ID's that change Your selectors break from development changes to CSS styles or JS behavior Luckily, it is possible to avoid both of these problems.

Don't target elements based on CSS attributes such as: id, class, tag Don't target elements that may change their textContent Add data-* attributes to make it easier to target elements


>

## Anything else
> Further information can be found here. 
https://docs.cypress.io/guides/references/best-practices#Selecting-Elements
https://medium.com/@auksirgul/data-attributes-hook-your-automated-tests-on-proper-selectors-3b601e8533c3

Interested to hear other people's thoughts. 
aircwo commented 1 year ago

@jamessan85 Think this should be transferred into a discussion?

I personally think that using a custom data variable within an element is just as clean as an identifier. Libraries such as cheerio can then be used to enable a whole range of tests for elements etc..

A good example of data in cheerio could be as straight forward as: const $ = cheerio.load(result.text) - (result.text being a snippet of html) $('[data-custom=sr-text]').text() - which will find the element with the data attribute and specific text which in this case is sr-text.

This makes the tests more readable as you know specifically that you're getting an element with a custom value with the data-custom then with the sr-text the specific custom element. This approach is also nifty when you have dynamic ids on elements or a list of the same element.

As far as I'm aware, approaches like this aren't used within the BSA.