Prompt
How do I keep selector-based tests stable when the DOM keeps changing?
Latest observation
Oct 27, 2026
OpenAI APIWeb search: off
To keep selector-based tests stable when the DOM changes often, focus on selecting elements by intent, not by layout or implementation details.
Good practices
- Prefer stable attributes: use
data-testid,data-qa, or similar.<button data-testid="save-button">Save</button> - Select by accessible role/name when possible:
- Buttons by role and label
- Inputs by label
- Links by text
- Avoid brittle selectors like:
- deep CSS chains
nth-child(...)- auto-generated class names
- DOM structure assumptions
Example
Instead of:
document.querySelector('div > div > ul > li:nth-child(2) > button')
Use:
screen.getByRole('button', { name: /save/i })
or:
screen.getByTestId('save-button')
Make selectors resilient
- Keep test selectors unique and consistent
- Don’t reuse the same test id for different elements
- Put the selector on the interactive element itself, not a wrapper, if possible
- If the UI changes frequently, create a small test contract:
- “This button will always have
data-testid="save-button"” - “This form field will always be labeled ‘Email’”
- “This button will always have
In component tests
If the DOM is dynamic, query through the user-facing surface:
- text
- labels
- roles
- placeholders only as a fallback
If elements are rendered conditionally
- Wait for them explicitly
- Query after state changes instead of assuming immediate presence
- Use retrying assertions in your test framework
Rule of thumb
If changing the DOM structure breaks your test but the user experience didn’t change, your selector is probably too implementation-specific.
If you want, I can show:
- a React Testing Library approach,
- a Playwright/Cypress approach, or
- a checklist for auditing flaky selectors.