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>);
  
  expect(getByText('Click')).toBeInTheDocument(); 
});

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>);
  
  fireEvent.click(getByText('Click'));
  
  expect(onClick).toHaveBeenCalledTimes(1); 
});

Assertion Matchers

Use matchers like toBeInTheDocument to make assertions:

// Assertion passes
expect(getByText('Click')).toBeInTheDocument();

// Assertion fails 
expect(getByText('Click')).not.toBeInTheDocument();

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.

Summary

  • 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.