JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
PrevNext
testing
mid
react-testing-library

How do you test React components with React Testing Library?

react-testing-library
component-testing
userEvent
queries
Quick Answer

React Testing Library tests components from the user's perspective. Use render() to mount components, query methods (getByRole, getByText, etc.) to find elements, fireEvent or userEvent for interactions, and waitFor for async updates.

Detailed Explanation

Philosophy:

  • Test behavior, not implementation
  • Query elements like users would find them
  • Avoid testing internal state/props

Query Methods:

  • getBy*: Throws if not found (sync)
  • queryBy*: Returns null if not found
  • findBy*: Returns Promise (async)

Query Priority:

  1. getByRole: Accessibility roles
  2. getByLabelText: Form elements
  3. getByPlaceholderText
  4. getByText: Non-form elements
  5. getByTestId: Last resort

User Events:

  • userEvent: More realistic than fireEvent
  • Simulates full interaction sequence

Code Examples

Basic component testing
// Counter.jsx
function Counter({ initialCount = 0 }) {
  const [count, setCount] = useState(initialCount);
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
      <button onClick={() => setCount(c => c - 1)}>Decrement</button>
    </div>
  );
}

// Counter.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Counter from './Counter';

describe('Counter', () => {
  test('renders initial count', () => {
    render(<Counter initialCount={5} />);
    
    expect(screen.getByText('Count: 5')).toBeInTheDocument();
  });

  test('increments count when button clicked', async () => {
    const user = userEvent.setup();
    render(<Counter />);
    
    await user.click(screen.getByRole('button', { name: /increment/i }));
    
    expect(screen.getByText('Count: 1')).toBeInTheDocument();
  });

  test('decrements count when button clicked', async () => {
    const user = userEvent.setup();
    render(<Counter initialCount={5} />);
    
    await user.click(screen.getByRole('button', { name: /decrement/i }));
    
    expect(screen.getByText('Count: 4')).toBeInTheDocument();
  });
});

Resources

React Testing Library Docs

docs

Testing Library Cheatsheet

docs

Related Questions

How do you mock functions, modules, and API calls in Jest?

mid
mocking

What is the difference between unit tests and integration tests?

mid
integration
Previous
How do you mock functions, modules, and API calls in Jest?
Next
What is the difference between unit tests and integration tests?