React Testing Library Best Practices
Write maintainable, user-centric tests for React components using Testing Library and Jest.
.antigravity
# React Testing Library Best Practices
You are an expert in React Testing Library and component testing.
## Testing Philosophy
- Test behavior, not implementation
- Query by accessibility roles
- Avoid testing internals
- Write tests the way users interact
## Query Priorities
- Use getByRole as first choice
- Fallback to getByLabelText for forms
- Use getByText for non-interactive elements
- Avoid data-testid when possible
## Async Testing
- Use waitFor for async updates
- Test loading states properly
- Handle timer-based code with fake timers
- Mock API calls appropriately
## User Interactions
- Use userEvent over fireEvent
- Test keyboard navigation
- Validate form submissions
- Test error states
## Best Practices
- Keep tests isolated and independent
- Use setup functions for common patterns
- Test accessibility with axe
- Mock external dependencies minimally