Testing your React components might sound intimidating, but with Jest, it’s actually fun! 🚀
In the era of AI, many people believe that Unit Testing is dead or no longer necessary. 🚫🤖 But let me tell you—it's one of the most underrated skills in software development! 💡✨
While most developers tend to skip it, thinking it's not essential, Unit Testing is actually a secret weapon 🛡️ that can elevate your code quality and save countless hours of debugging. 🐛⏱️
In fact, I believe that learning Unit Testing is far more important than jumping on the bandwagon of the next shiny framework. 🚀📚
Mastering this skill will not only make your codebase more reliable but also make you a better developer. 💻✅
In this blog, I'll dive into Jest for unit testing React components.Let’s get our hands dirty! 💪
🔹 Why Jest?
Before we jump in, why should you even care about Jest?
Jest is a delightful JavaScript testing framework created by Facebook
. It’s fast
, easy to set up
, and works seamlessly with React
.
Plus, it comes with built-in support for mocking
, assertions
, and code coverage
. 🛠️
Alright, enough chit-chat. Let’s code! 💪
📦 Setting Up Jest
- Create React App (already comes with Jest):
npx create-react-app my-app
cd my-app
npm test
Boom! Jest is running. 🚀 But this method is deprecated so we can use other module bundler like Vite, Webpack etc. and setup jest manually.
- Manual Setup:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
🔧 Writing Your First Test
Let’s create a simple component and test it!
Counter.js
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1 data-testid="count">{count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default Counter;
📖 Counter.test.js
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import Counter from './Counter';
test('renders initial count', () => {
render(<Counter />);
const countElement = screen.getByTestId('count');
expect(countElement).toHaveTextContent('0');
});
test('increments count on button click', () => {
render(<Counter />);
const buttonElement = screen.getByText('Increment');
fireEvent.click(buttonElement);
const countElement = screen.getByTestId('count');
expect(countElement).toHaveTextContent('1');
});
🚀 Run Tests
npm run test
You should see green checkmarks! 😃🔹
📊 Snapshot Testing
Want to make sure your UI doesn’t change unexpectedly? Use snapshots! 📸
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import Counter from './Counter';
test('matches snapshot', () => {
const { asFragment } = render(<Counter />);
expect(asFragment()).toMatchSnapshot();
});
Run the test, and Jest will create a snapshot file. Next time you run tests, it will compare the current UI to the saved snapshot.
🔐 Mocking Functions
Sometimes, you need to mock functions to isolate your component's behavior.
Greeting.js
import React, { useEffect, useState } from 'react';
const Greeting = ({ fetchGreeting }) => {
const [greeting, setGreeting] = useState('');
useEffect(() => {
fetchGreeting().then(setGreeting);
}, [fetchGreeting]);
return <h1>{greeting}</h1>;
};
export default Greeting;
Greeting.test.js
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import Greeting from './Greeting';
test('renders greeting from API', async () => {
const mockFetchGreeting = jest.fn().mockResolvedValue('Hello, Jest!');
render(<Greeting fetchGreeting={mockFetchGreeting} />);
const greetingElement = await screen.findByText('Hello, Jest!');
expect(greetingElement).toBeInTheDocument();
});
🚀 Tips for Better Testing
- Test Behavior, Not Implementation: Focus on what the component does, not how it does it.
- Keep Tests Isolated: Don’t let tests depend on each other.
-
Use
beforeEach
for Repeated Setup: Clean and DRY code! 💡
🎓 Your Challenge!
Now it’s your turn! 🚀 Create a TodoList
component with the following features:
- Display a list of tasks.
- Add new tasks.
- Mark tasks as completed.
For code you can take reference from this blog of mine:

Reactjs Todo List App (Using Vite & Zustand)
Jagroop Singh ・ Sep 16 '24
Challenge: Write unit tests for each feature! Share your code in the comments 🚀✨
Happy Testing! 💡🌟 Let me know how your testing journey goes! 🚀
Your blogs makes complicated stuffs to easy to understand concepts about new things. I really understand each and every part of this blog. I will try this on Todo List App.