Testing React Apps: Beginner's Guide to TDD

Testing is crucial for ensuring React apps are stable and bug-free. Popular tools like Jest and React Testing Library make testing React components simple.

Let’s look at how to write great tests for React:

render Component

Render the component into a test environment using render from React Testing Library:

import { render } from '@testing-library/react';
import Button from './Button';

test('displays button text', () => {
  const { getByText } = render(<Button>Click</Button>);

This renders the component virtually for testing.

Fire Events

Simulate user events like clicks with fireEvent:

test('calls onClick prop on click', () => {
  const onClick = jest.fn();
  const { getByText } = render(<Button onClick={onClick}>Click</Button>);

Assertion Matchers

Use matchers like toBeInTheDocument to make assertions:

// Assertion passes

// Assertion fails 

Mock Functions

Spy on callbacks with mock functions:

const handleChange = jest.fn();

// interact with component 

expect(handleChange).toHaveBeenCalledWith('input value');

This allows asserting function calls.


  • Use render to mount components
  • Fire events to simulate interaction
  • Make assertions with matchers
  • Spy on callbacks with mock functions

Automated testing results in robust React components you can refactor with confidence.