Overview
Component testing ensures your React components render correctly and behave as expected. Using React Testing Library with Vitest, you can write tests that closely resemble how users interact with your application.Basic Component Test Structure
Every test follows a clear structure:- Arrange: Set up the test data and render the component
- Act: Perform actions (if needed)
- Assert: Verify the expected outcome
Testing Component Rendering
Let’s examine a real component from the codebase:MyAwesomeApp.tsx
Query Methods: Container vs Screen
React Testing Library offers two approaches for querying elements:The
screen approach is recommended by React Testing Library as it’s more concise and encourages accessible queries. Use data-testid attributes when you can’t query by role, label, or text.Testing Helper Functions
Unit tests for pure functions follow the Arrange-Act-Assert pattern clearly:math.helper.ts
Testing Pure Functions
math.helper.test.ts
Debugging Tests
Usescreen.debug() to print the current DOM state:
screen.debug() is invaluable for understanding what React Testing Library “sees” in your component. Use it when tests fail unexpectedly.Best Practices
- Use data-testid sparingly: Prefer querying by role, label, or text content
- Test user behavior: Focus on what users see and do, not implementation details
- Keep tests simple: Each test should verify one specific behavior
- Use descriptive test names: Test names should clearly state what is being tested
- Follow AAA pattern: Always structure tests with Arrange, Act, Assert
Common Queries
getByTestId(): Query by data-testid attributegetByRole(): Query by ARIA role (button, heading, etc.)getByText(): Query by text contentgetByLabelText(): Query form elements by labelqueryBy*(): Returns null if not found (for negative assertions)findBy*(): Async queries that wait for elements
Next Steps
- Learn about snapshot testing to catch UI regressions
- Explore async testing with
findByqueries - Add test coverage reporting to your workflow