</>
Skip to content
React lessons (38/47)

React — Testing

Setup

npm install --save-dev @testing-library/react @testing-library/jest-dom

Basic Test

// App.test.js
import { render, screen } from '@testing-library/react';
import App from './App';

test('renders hello world', () => {
    render(<App />);
    const linkElement = screen.getByText(/hello world/i);
    expect(linkElement).toBeInTheDocument();
});

Testing Components

// Button.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';

test('renders button with text', () => {
    render(<Button>Click me</Button />);
    expect(screen.getByText('Click me')).toBeInTheDocument();
});

test('calls onClick when clicked', () => {
    const handleClick = jest.fn();
    render(<Button onClick={handleClick}>Click me</Button>);

    fireEvent.click(screen.getByText('Click me'));
    expect(handleClick).toHaveBeenCalledTimes(1);
});

Testing Async Code

// DataFetcher.test.js
import { render, screen, waitFor } from '@testing-library/react';
import DataFetcher from './DataFetcher';

test('fetches and displays data', async () => {
    global.fetch = jest.fn(() =>
        Promise.resolve({
            json: () => Promise.resolve({ name: 'John' }),
        })
    );

    render(<DataFetcher />);

    await waitFor(() => {
        expect(screen.getByText('John')).toBeInTheDocument();
    });
});

Testing Examples

// Form testing
test('submits form with correct data', () => {
    const handleSubmit = jest.fn();
    render(<Form onSubmit={handleSubmit} />);

    fireEvent.change(screen.getByPlaceholderText('Name'), {
        target: { value: 'John' },
    });

    fireEvent.change(screen.getByPlaceholderText('Email'), {
        target: { value: 'john@example.com' },
    });

    fireEvent.click(screen.getByText('Submit'));

    expect(handleSubmit).toHaveBeenCalledWith({
        name: 'John',
        email: 'john@example.com',
    });
});

// Testing hooks
test('useCounter increments count', () => {
    const { result } = renderHook(() => useCounter(0));

    act(() => {
        result.current.increment();
    });

    expect(result.current.count).toBe(1);
});

// Testing context
test('provides theme context', () => {
    render(
        <ThemeProvider>
            <ThemedComponent />
        </ThemeProvider>
    );

    expect(screen.getByTestId('theme')).toHaveTextContent('light');
});

Test Utilities

UtilityDescription
renderRenders a component
screenQuery the rendered output
fireEventSimulate events
waitForWait for async updates
actWrap state updates

Mini Practice

Write React code that:

  1. Tests a simple component
  2. Tests event handling
  3. Tests async operations
  4. Tests form submission

Up Next

Next: Learn about Deployment.

Related Topics

Frequently Asked Questions about Testing

What is Testing in React?

Testing is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Testing?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Testing.

Why is Testing important in React?

Testing is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.