As a React developer with over eight years of experience, I’ve seen firsthand how testing can make or break the quality of an application. When I first started writing tests for React components, it felt overwhelming. But once I got the hang of Jest, the popular testing framework, and combined it with React Testing Library, testing became an integral, even enjoyable part of my development workflow.
In this article, I’ll walk you through how to write Jest tests for React components with practical examples that fit real-world scenarios, especially for developers working in the USA market. Whether you’re new to testing or looking to improve your current approach, this guide will help you write effective, maintainable tests.
Test React Components with Jest
Testing React components ensures your UI behaves as expected, especially when users interact with your app. In the USA, where user experience and accessibility are crucial, tests help catch bugs early and maintain high-quality standards.
Jest is the go-to testing framework for React because it’s fast, easy to set up, and comes with powerful features like mocking and snapshot testing. Combined with React Testing Library, it encourages writing tests that resemble how users interact with your app, making your tests more reliable.
Set Up Jest and React Testing Library
If you’re starting a new React project, create it with Create React App (CRA), which comes pre-configured with Jest.
npx create-react-app usa-productivity-app
cd usa-productivity-appFor existing projects, install React Testing Library:
npm install --save-dev @testing-library/react @testing-library/jest-domAdd this import to your test files to use helpful matchers:
import '@testing-library/jest-dom';Method 1: Test a Simple React Component
Let’s start with a simple example: a ProductivityTimer component that tracks work sessions.
// src/components/ProductivityTimer.js
import React, { useState } from 'react';
const ProductivityTimer = () => {
const [seconds, setSeconds] = useState(0);
const [running, setRunning] = useState(false);
const startTimer = () => setRunning(true);
const stopTimer = () => setRunning(false);
const resetTimer = () => setSeconds(0);
React.useEffect(() => {
let interval = null;
if (running) {
interval = setInterval(() => {
setSeconds(prev => prev + 1);
}, 1000);
} else if (!running && seconds !== 0) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [running, seconds]);
return (
<div>
<h1>Work Timer: {seconds} seconds</h1>
<button onClick={startTimer} disabled={running}>Start</button>
<button onClick={stopTimer} disabled={!running}>Stop</button>
<button onClick={resetTimer}>Reset</button>
</div>
);
};
export default ProductivityTimer;Write Tests with Jest and React Testing Library
Create a test file:
// src/components/ProductivityTimer.test.js
import React from 'react';
import { render, screen, fireEvent, act } from '@testing-library/react';
import ProductivityTimer from './ProductivityTimer';
jest.useFakeTimers();
test('renders timer and buttons', () => {
render(<ProductivityTimer />);
expect(screen.getByText(/Work Timer/i)).toBeInTheDocument();
expect(screen.getByText('Start')).toBeInTheDocument();
expect(screen.getByText('Stop')).toBeInTheDocument();
expect(screen.getByText('Reset')).toBeInTheDocument();
});
test('starts and stops the timer', () => {
render(<ProductivityTimer />);
const startButton = screen.getByText('Start');
const stopButton = screen.getByText('Stop');
const timerText = screen.getByText(/Work Timer/i);
// Start the timer
fireEvent.click(startButton);
expect(startButton).toBeDisabled();
expect(stopButton).not.toBeDisabled();
// Fast-forward 3 seconds
act(() => {
jest.advanceTimersByTime(3000);
});
expect(timerText).toHaveTextContent('Work Timer: 3 seconds');
// Stop the timer
fireEvent.click(stopButton);
expect(startButton).not.toBeDisabled();
expect(stopButton).toBeDisabled();
});
test('resets the timer', () => {
render(<ProductivityTimer />);
const startButton = screen.getByText('Start');
const resetButton = screen.getByText('Reset');
const timerText = screen.getByText(/Work Timer/i);
fireEvent.click(startButton);
act(() => {
jest.advanceTimersByTime(5000);
});
expect(timerText).toHaveTextContent('Work Timer: 5 seconds');
fireEvent.click(resetButton);
expect(timerText).toHaveTextContent('Work Timer: 0 seconds');
});I executed the above example code and added the screenshot below.

- We use jest.useFakeTimers() to control time-based functions.
- act() wraps the timer advancement to ensure React updates are processed.
- We test UI elements and user interactions like clicking buttons.
This method is easy and works well for components with state and side effects.
Method 2: Snapshot Testing for UI Stability
Snapshot testing helps you track UI changes over time. It’s useful for components that don’t change often or have static content.
Here’s how to add a snapshot test for the same component:
import React from 'react';
import renderer from 'react-test-renderer';
import ProductivityTimer from './ProductivityTimer';
test('matches snapshot', () => {
const tree = renderer.create(<ProductivityTimer />).toJSON();
expect(tree).toMatchSnapshot();
});Run your tests with:
npm testI executed the above example code and added the screenshot below.

The first time, Jest creates a snapshot file. Later runs compare the rendered output to this snapshot and alert you if there are unexpected changes.
Method 3: Mock API Calls in React Components
In many USA-based applications, components fetch data from APIs, like productivity reports or user stats. Testing these requires mocking fetch or axios calls.
Here’s an example component that fetches user productivity data:
// src/components/UserProductivity.js
import React, { useEffect, useState } from 'react';
const UserProductivity = ({ userId }) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(`https://api.usa-productivity.com/users/${userId}/stats`)
.then(res => res.json())
.then(json => {
setData(json);
setLoading(false);
});
}, [userId]);
if (loading) return <p>Loading...</p>;
return (
<div>
<h2>{data.name}'s Productivity</h2>
<p>Tasks completed: {data.tasksCompleted}</p>
<p>Hours worked: {data.hoursWorked}</p>
</div>
);
};
export default UserProductivity;Writing a Test with Mocked Fetch
// src/components/UserProductivity.test.js
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import UserProductivity from './UserProductivity';
beforeEach(() => {
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({
name: 'John Doe',
tasksCompleted: 42,
hoursWorked: 160,
}),
})
);
});
afterEach(() => {
jest.resetAllMocks();
});
test('displays user productivity data', async () => {
render(<UserProductivity userId="123" />);
expect(screen.getByText(/Loading/i)).toBeInTheDocument();
await waitFor(() => expect(screen.getByText(/John Doe's Productivity/i)).toBeInTheDocument());
expect(screen.getByText(/Tasks completed: 42/i)).toBeInTheDocument();
expect(screen.getByText(/Hours worked: 160/i)).toBeInTheDocument();
});Mocking API calls like this ensures your tests are fast and don’t depend on external services.
Tips from My Experience
- Write tests as you build components. It’s easier than retrofitting tests later.
- Focus on user interactions, not implementation details. This makes tests more robust.
- Use descriptive test names. It helps when tests fail and you need to debug.
- Run tests frequently. Integrate them with your CI pipeline to catch issues early.
- Keep tests isolated. Avoid dependencies between tests to prevent flaky results.
Testing React components with Jest and React Testing Library has been a game-changer in my projects. It helps me deliver reliable applications that users in the USA can trust. Whether it’s a simple timer or a complex data-driven dashboard, testing ensures quality and confidence in every release.
If you haven’t started testing yet, give these methods a try. You’ll be surprised how much smoother development becomes when you catch bugs before they reach production.
Related articles you might like:
- Component Driven Development in React
- Use Dynamic Component Names in React
- React Functional Component Props
- Solve “Could Not Find React-Redux Context Value” Error in React

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.