CSS modules add ID's to the classes e.g. classUc8xi
.
Since we want to target some elements with Cypress which uses some sort of QuerySelector, I want to know if these ID's ever change? Are they constant and identical for every user?
Is it a good idea to add these ID's to our Cypress tests like below or are there better options?
selectBtn: '[class="select-buttonUc8xi"]'
The purpose of the Uc8xi
is to scope the CSS to that particular component, i.e to stop CSS from one component from "bleeding" to another similar component.
The suffix chars is likely to be generated somewhat randomly, so no don't use that class as a selector.
Either add non-module CSS (it won't have a suffix), or explicitly add a data-test
attribute to use instead.
Note that some React components won't pass the data-test
on to the HTML page, you might have to add it to the topmost "concrete" element that renders on the component.
For example:
function Welcome(props) {
return <h1 data-test="my-hello">Hello, {props.name}</h1>; // data-test id here
}
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" data-test="my-hello" />; // not here
root.render(element);
Test
cy.get('[data-test="my-hello"]')
.should('have.text', 'Hello, Sara')