🚀 Setting Up a React Project with Vite
September 25, 2024
1 min
Testing your React components is essential for maintaining a stable and scalable codebase. In this guide, you’ll learn how to set up @testing-library/react
and Jest from scratch to test React components in a clean and user-focused way.
@testing-library/react
helps you write tests that interact with your app like a real user.Together, they provide a robust solution for testing the behavior of your UI, not the implementation details.
If you’re using Create React App, it already includes Jest. Otherwise, you can install everything manually.
npm install --save-dev jest @testing-library/react @testing-library/jest-dom @testing-library/user-event
If you use TypeScript:
npm install --save-dev ts-jest @types/jest
Create a jest.config.js
file in the root of your project:
// jest.config.jsmodule.exports = {preset: 'ts-jest', // Use 'babel-jest' if you're using Babel instead of TypeScripttestEnvironment: 'jsdom',setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],};
Then create a jest.setup.js
file to include extended matchers like toBeInTheDocument()
:
// jest.setup.jsimport '@testing-library/jest-dom';
Counter.tsx
import { useState } from 'react';export function Counter() {const [count, setCount] = useState(0);return (<div><p>Count: {count}</p><button onClick={() => setCount(count + 1)}>Increment</button></div>);}
Counter.test.tsx
import { render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { Counter } from './Counter';test('increments count when button is clicked', async () => {render(<Counter />);expect(screen.getByText(/count: 0/i)).toBeInTheDocument();const button = screen.getByRole('button', { name: /increment/i });await userEvent.click(button);expect(screen.getByText(/count: 1/i)).toBeInTheDocument();});
Add this to your package.json
scripts:
"scripts": {"test": "jest"}
Then run:
npm test
You’ll see output like:
PASS src/Counter.test.tsx✓ increments count when button is clicked (30 ms)
screen.getByRole()
or getByText()
instead of class or ID selectors.userEvent
instead of fireEvent
for more realistic user interaction.jest.mock()
to mock API or context providers when needed.Quick Links
Legal Stuff
Social Media