← Back to React Testing Library Mastery
Advanced18 min read

Best Practices

Write maintainable RTL tests avoiding implementation details and common pitfalls.

Test Organization

Co-locate Component.test.tsx with source. One describe per component or feature area. Name tests as user-observable outcomes.

Extract repeated setup to beforeEach or setup helper—not copy-paste render blocks.

  • Keep tests under 30 lines when possible for readability
  • Group happy path before edge cases and errors
  • Share factory functions for default props

Maintainability

Query by role/label survives CSS module renames. Avoid data-testid proliferation—use only when no accessible query exists.

When test breaks, ask: did user experience break? If no, fix test not code.

// Prefer
screen.getByRole("button", { name: /save/i });

// Avoid
container.querySelector(".btn-primary");

Coverage

Aim for confidence on critical paths over 100% line coverage. Test error states, empty states, loading, permission denied.

Coverage tools integrate with Jest and Vitest—exclude stories and test-utils from metrics.

  • Integration tests through container components complement leaf unit tests
  • Do not test third-party library behavior—trust documented API
  • Delete tests that duplicate identical assertion across files

Avoiding Implementation Details

Do not assert component state, prop names internal to child, or call count on hooks unless hook unit test. Do not shallow render children stubs replacing real integration.

Testing Library eslint plugin enforces query priority and no-node-access rules.

// eslint-plugin-testing-library recommended rules in .eslintrc

Team Culture

Review tests in PR with same rigor as production code. Flaky tests fixed or quarantined immediately. Document custom render and MSW handlers for onboarding.

Celebrate deleting obsolete tests when feature removed—reduce maintenance burden.

  • Run tests in CI on every PR—protected branch required
  • Prefer few strong tests over many brittle ones
  • Align with Kent C. Dodds guiding principles article

Get In Touch


Ready to discuss your next project? Drop me a message.