Prompt
How do I keep end-to-end tests from breaking when the DOM changes?
Latest observation
To make end-to-end tests less brittle when the DOM changes, focus on testing user-visible behavior and use stable selectors.
Best practices
1) Prefer semantic selectors over CSS structure
Avoid selectors that depend on layout or nesting, like:
.sidebar > div:nth-child(2) > button#app > main > section > div:nth-of-type(3)
These break easily when markup changes.
Instead use:
- accessible roles:
button,textbox,heading, etc. - accessible names: visible text, labels, aria-labels
- test IDs only when needed
Examples:
- Playwright
await page.getByRole('button', { name: 'Save' }).click(); await page.getByLabel('Email').fill('a@example.com'); - Testing Library
screen.getByRole('button', { name: /save/i }); screen.getByLabelText(/email/i);
2) Add stable attributes for testing
If your UI text or structure changes often, add explicit test hooks:
<button data-testid="save-button">Save</button>
Then use:
await page.getByTestId('save-button').click();
Use this as a fallback, not the default.
3) Test outcomes, not implementation details
Assert what the user experiences:
- page navigates
- confirmation message appears
- item is added to the list
- network request is triggered and UI updates
Avoid asserting exact DOM structure, class names, or precise element counts unless that is the behavior under test.
4) Use resilient waits
Don’t rely on arbitrary sleeps like waitForTimeout(2000). Wait for:
- elements to appear
- text to be visible
- requests to complete
- URL changes
Examples:
await expect(page.getByText('Saved successfully')).toBeVisible();
await page.waitForURL('**/dashboard');
5) Keep selectors close to user intent
Name actions after the user task, not the implementation:
- “click submit order”
- “find user by email”
- “open settings”
This makes tests easier to update when the UI changes.
6) Separate critical paths from UI details
Keep a small set of end-to-end tests for major workflows:
- login
- checkout
- create/edit/delete core entities
Use component/unit tests for detailed DOM behavior. This reduces how much you depend on the exact page structure in E2E.
7) If possible, align with accessibility
A good side effect: if your app has proper labels/roles, your tests become more stable and your UI more accessible.
Rule of thumb
If changing the DOM breaks the test but the user experience didn’t change, the test is probably too tightly coupled to implementation.
If you want, I can show examples for Playwright, Cypress, or Selenium specifically.