Why do tests of internal state and CSS classes fail refactors?
Question
A team tests <InviteForm onInvite={onInvite} /> with this suite:
const { container } = render(<InviteForm onInvite={onInvite} />);
const input = container.querySelector('.invite-input');
const btn = container.querySelector('.btn-primary-active');
fireEvent.change(input, { target: { value: '[email protected]' } });
fireEvent.submit(container.querySelector('form'));
expect(btn.getAttribute('data-state')).toBe('submitting');Renaming .btn-primary-active to .submit-cta broke this test even though the form still worked. Later, a bug left the Submit button disabled and hid the invalid-email error, yet the test still passed.
- Why did this test produce both a false failure and a false pass?
- Rewrite the test around accessible queries,
userEvent, and visible outcomes.
Show hints (3)
- "TEST PUBLIC BEHAVIOR"
Users never read
.btn-primary-activeordata-state. They find a labeled field, type an email, click a named button, and read an alert or confirmation. - "USER-EVENT OVER FIREEVENT"
fireEvent.submit(form)bypasses adisabledSubmit button, andfireEvent.clickignorespointer-events: none.userEvent.clickrespects browser interaction rules. - "ASSERT VISIBLE RESULTS"
Query via
getByLabelTextandgetByRole('button', { name }). Check both the invalid-emailrole="alert"message andonInvite('[email protected]')on valid submit.
Show checked explanation
Tests coupled to private CSS classes (.btn-primary-active) or internal attributes (data-state) fail on harmless refactors (false failures). Meanwhile, fireEvent.submit(form) bypasses a disabled Submit button and never checks visible alerts or callbacks (false passes). Query by accessible label and role, act with userEvent.setup(), and assert visible DOM outcomes and callbacks.
Brittle selector and user-behavior tests were executed against four InviteForm variants (original, CSS/state refactor, stuck-disabled button, and hidden-error bug) in a mock DOM and Testing Library harness on Node.js v24.15.0 via Python 3.12.10 (no jsdom or React Testing Library package installed); query priority and user-event semantics checked against Testing Library and MDN documentation. Checked by an editor other than the author.
Walkthrough
Implementation-detail tests hurt you in both directions. They fail when you improve styling or switch useState to useReducer, and they stay green when a real user cannot submit the form.
InviteForm change | Brittle class + fireEvent test | Accessible role + userEvent test |
|---|---|---|
| Working form | Passes | Passes |
Rename CSS class + switch to useReducer | Fails (false failure) | Passes |
Bug: <button disabled> stays stuck | Passes (false pass!) | Fails (toBeEnabled + user.click) |
Bug: error hidden or missing role="alert" | Passes (never checked) | Fails (no visible alert) |
1. Query the way users find controls. Follow Testing Library's query priority: getByRole (with { name }) and getByLabelText come first, getByText next, and getByTestId only as a last resort when no semantic label exists. Querying getByLabelText(/work email/i) also catches broken <label htmlFor> links automatically.
2. Drive actions with userEvent.setup(). Low-level fireEvent.submit(form) fires onSubmit directly even when <button type="submit" disabled> blocks real users, and fireEvent.click ignores pointer-events: none. userEvent.click runs the full pointer, focus, and click sequence and refuses to trigger disabled controls.
3. Assert visible behavior for both failure and success:
const user = userEvent.setup();
render(<InviteForm onInvite={onInvite} />);
const email = screen.getByLabelText(/work email/i);
const submit = screen.getByRole('button', { name: /send invite/i });
await user.type(email, 'bad-email');
await user.click(submit);
expect(screen.getByRole('alert')).toHaveTextContent(/valid email/i);
expect(onInvite).not.toHaveBeenCalled();
await user.clear(email);
await user.type(email, '[email protected]');
expect(submit).toBeEnabled();
await user.click(submit);
expect(onInvite).toHaveBeenCalledWith('[email protected]');Now you can swap CSS frameworks or rewrite hooks internally without breaking the suite, while any broken label, stuck button, or hidden error fails immediately.
Common mistakes
- Using
container.querySelector('.btn-primary-active')instead ofscreen.getByRole('button', { name }). Every style rename breaks tests without protecting users. - Dispatching
fireEvent.submit(form)or low-levelfireEvent.clickfor normal interactions. Synthetic events bypassdisabledbuttons orpointer-events: noneand hide real user bugs. - Spying on internal helper functions or hook state instead of rendered DOM text and component props like
onInvite. - Reaching for
data-testidon every input and button first. Users and screen readers never seedata-testid, so broken labels slip into production.
Follow-up questions
- "When is
data-testidactually reasonable in a component test?" UsegetByTestIdonly when an element has no meaningful accessible role, label, or stable text, such as a canvas chart or a dynamic container whose text changes by locale. Always tryByRoleandByLabelTextfirst. - "How do you test a custom hook without coupling component tests to its internal state?" For app-specific hooks, test them through the real component that uses them so DOM behavior stays covered. Reach for
renderHookonly for shared reusable hooks published as an internal library API. - "Why check
expect(screen.getByRole('alert')).toBeVisible()(or visible text) instead of only checking that an error node exists in the DOM?" A component can keep an error<div>mounted withhiddenordisplay: none. Checkingrole="alert"and visibility confirms both sighted users and screen readers actually receive the error.
What a strong answer covers
Explains both false failures (CSS/hook refactors) and false passes (fireEvent.submit bypassing a disabled button), applies Testing Library query priority (ByLabelText, ByRole), uses userEvent.setup(), and tests both error and submit outcomes.
Open in interactive practice deck →