HomeAbout Me

Setting Up `@testing-library/react` and `Jest` for React Component Testing

By Daniel Nguyen
Published in React JS
September 25, 2024
1 min read
Setting Up `@testing-library/react` and `Jest` for React Component Testing

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.


🔧 Why Use @testing-library/react and Jest?

  • @testing-library/react helps you write tests that interact with your app like a real user.
  • Jest is a powerful JavaScript testing framework with built-in support for assertions, mocking, and test runners.

Together, they provide a robust solution for testing the behavior of your UI, not the implementation details.


📦 Installation

If you’re using Create React App, it already includes Jest. Otherwise, you can install everything manually.

For non-CRA projects (e.g., Vite, Webpack, etc.):

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

⚙️ Jest Configuration

Create a jest.config.js file in the root of your project:

// jest.config.js
module.exports = {
preset: 'ts-jest', // Use 'babel-jest' if you're using Babel instead of TypeScript
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};

Then create a jest.setup.js file to include extended matchers like toBeInTheDocument():

// jest.setup.js
import '@testing-library/jest-dom';

🧪 Example React Component and Test

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();
});

🚀 Running the Tests

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)

🧠 Tips for Writing Better Tests

  • Prefer screen.getByRole() or getByText() instead of class or ID selectors.
  • Use userEvent instead of fireEvent for more realistic user interaction.
  • Use jest.mock() to mock API or context providers when needed.
  • Test the behavior, not the implementation.

📚 Useful Resources

  • Testing Library Docs
  • Jest Docs
  • React Testing Best Practices


Tags

#React

Share

Previous Article
🚀 Setting Up a React Project with Vite
Next Article
Writing 1

Table Of Contents

1
🔧 Why Use @testing-library/react and Jest?
2
📦 Installation
3
⚙️ Jest Configuration
4
🧪 Example React Component and Test
5
🚀 Running the Tests
6
🧠 Tips for Writing Better Tests
7
📚 Useful Resources

Related Posts

🚀 Setting Up a React Project with Vite
September 25, 2024
1 min
© 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media