Setup
npm install --save-dev @testing-library/react @testing-library/jest-dom jest
Basic Component Test
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import Counter from './Counter';
test('increments count on button click', () => {
render(<Counter />);
const button = screen.getByRole('button', { name: /increment/i });
fireEvent.click(button);
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
Testing Async Components
test('loads and displays user data', async () => {
render(<UserProfile userId={1} />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByText('Alice')).toBeInTheDocument();
});
Mocking API Calls
beforeEach(() => {
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ name: 'Alice' }),
})
);
});
afterEach(() => jest.restoreAllMocks());
test('displays user name after fetch', async () => {
render(<UserProfile userId={1} />);
expect(await screen.findByText('Alice')).toBeInTheDocument();
expect(fetch).toHaveBeenCalledWith('/api/users/1');
});
Ready to Level Up Your Coding Skills?
Join Coderz Club and learn to code with challenges, battles, and an AI mentor.
Join Coderz Club Free →