download

Why do tests of internal state and CSS classes fail refactors?

Frontend~8 minReviewed 3 Dec 2026Free · No sign-in

Question

A team tests <InviteForm onInvite={onInvite} /> with this suite:

"JAVASCRIPT"
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.

  1. Why did this test produce both a false failure and a false pass?
  2. Rewrite the test around accessible queries, userEvent, and visible outcomes.
Show hints (3)
  1. "TEST PUBLIC BEHAVIOR"

    Users never read .btn-primary-active or data-state. They find a labeled field, type an email, click a named button, and read an alert or confirmation.

  2. "USER-EVENT OVER FIREEVENT"

    fireEvent.submit(form) bypasses a disabled Submit button, and fireEvent.click ignores pointer-events: none. userEvent.click respects browser interaction rules.

  3. "ASSERT VISIBLE RESULTS"

    Query via getByLabelText and getByRole('button', { name }). Check both the invalid-email role="alert" message and onInvite('[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 changeBrittle class + fireEvent testAccessible role + userEvent test
Working formPassesPasses
Rename CSS class + switch to useReducerFails (false failure)Passes
Bug: <button disabled> stays stuckPasses (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:

"JAVASCRIPT"
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 of screen.getByRole('button', { name }). Every style rename breaks tests without protecting users.
  • Dispatching fireEvent.submit(form) or low-level fireEvent.click for normal interactions. Synthetic events bypass disabled buttons or pointer-events: none and 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-testid on every input and button first. Users and screen readers never see data-testid, so broken labels slip into production.

Follow-up questions

  • "When is data-testid actually reasonable in a component test?" Use getByTestId only 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 try ByRole and ByLabelText first.
  • "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 renderHook only 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 with hidden or display: none. Checking role="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 →

Original OfferVibe question. Testing Library Guiding Principles · Testing Library Query Priority · Testing Library user-event · ARIA alert role (MDN).
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.