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.
Figure 16: The Testing Trophy: High-Return Integration Tests (RTL) Over Low-Level Unit Tests.
// 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');
});
});
Now let us examine web security and XSS attack prevention in React Security Best Practices.
Accelerate your React mastery by studying these tightly connected core tutorials:
Verifying rendered elements and user accessibility.
fireEvent and userEvent in React Testing Library.
renderHook utility in Vitest and Jest.