React Testing: Unit & Integration Testing with React Testing Library

Writing automated tests gives engineering teams the confidence to ship updates without breaking existing functionality. In the React ecosystem, the gold standard testing combination is Vitest (or Jest) as the test runner, paired with React Testing Library (RTL) for rendering components and asserting user behavior.

React Testing Trophy Diagram

Figure 16: The Testing Trophy: High-Return Integration Tests (RTL) Over Low-Level Unit Tests.

Writing an Integration Test with React Testing Library

// src/components/__tests__/Counter.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect } from 'vitest';
import Counter from '../Counter';

describe('Counter Component Integration Tests', () => {
  it('renders initial count of 0', () => {
    render(<Counter />);
    // Query DOM by accessible role and visible text
    expect(screen.getByRole('heading', { level: 3 })).toHaveTextContent('Count: 0');
  });

  it('increments count when user clicks increment button', async () => {
    const user = userEvent.setup();
    render(<Counter />);

    const incrementButton = screen.getByRole('button', { name: /increment/i });
    
    // Simulate realistic user click event
    await user.click(incrementButton);
    await user.click(incrementButton);

    // Verify UI reflects new state
    expect(screen.getByRole('heading', { level: 3 })).toHaveTextContent('Count: 2');
  });
});

Next Step: Security Best Practices

Now let us examine web security and XSS attack prevention in React Security Best Practices.

Explore Related React JS Tutorials

Accelerate your React mastery by studying these tightly connected core tutorials:

Testing Component Output →

Verifying rendered elements and user accessibility.

Simulating User Events →

fireEvent and userEvent in React Testing Library.

Testing Custom Hooks →

renderHook utility in Vitest and Jest.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!