Tillitsdone
down Scroll to discover

Testing React Components: Jest & RTL Best Practices

Learn essential best practices for testing React components using Jest and React Testing Library.

Discover how to write maintainable tests that focus on behavior and user interaction.
thumbnail

Best Practices for Testing React Components with Jest and React Testing Library

A cosmic nebula with swirling patterns in bright dusty lavender and sky blue colors featuring ethereal wisps and stellar formations ultra-realistic cinematic 8K UHD high resolution sharp and detailed

Testing is a crucial part of building reliable React applications. When done right, it gives you confidence in your code and makes refactoring a breeze. Let’s dive into the best practices for testing React components using Jest and React Testing Library.

Setting Up Your Testing Environment

Before we jump into writing tests, make sure you have the right tools installed. If you’re using Create React App, Jest and React Testing Library come pre-configured. Otherwise, you’ll need to install:

Terminal window
npm install --save-dev jest @testing-library/react @testing-library/jest-dom

Key Principles to Remember

  1. Test behavior, not implementation
  2. Write tests from the user’s perspective
  3. Find elements the way users would
  4. Keep tests maintainable and readable

Abstract geometric shapes floating in space with minimal mustard yellow and bright sky blue gradients featuring crystalline structures high-quality ultra-realistic cinematic 8K UHD sharp and detailed

Writing Your First Test

Here’s a practical example of testing a simple button component:

import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';
test('calls onClick prop when clicked', () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick}>Click me</Button>);
fireEvent.click(screen.getByText('Click me'));
expect(handleClick).toHaveBeenCalledTimes(1);
});

Best Practices for Element Selection

  1. Prefer getByRole over getByTestId
  2. Use getByLabelText for form elements
  3. Resort to getByTestId only when necessary

Example of good element selection:

// ❌ Don't
getByTestId('submit-button')
// ✅ Do
getByRole('button', { name: /submit/i })

Flowing abstract patterns resembling coral reefs in bright dusty lavender and minimal white colors with organic shapes and textures high-quality ultra-realistic cinematic 8K UHD sharp and detailed

Testing Async Operations

When testing components that fetch data or handle async operations:

test('displays data after fetch', async () => {
render(<UserProfile userId="123" />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
await screen.findByText('User Profile');
expect(screen.getByText('John Doe')).toBeInTheDocument();
});

Testing Custom Hooks

For testing custom hooks, use the renderHook utility:

import { renderHook, act } from '@testing-library/react-hooks';
import useCounter from './useCounter';
test('increments counter', () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});

Common Pitfalls to Avoid

  1. Don’t test implementation details
  2. Avoid snapshot tests for complex components
  3. Don’t test third-party component internals
  4. Keep tests focused and isolated

Testing Complex Components

For components with multiple states or complex interactions:

test('form submission workflow', async () => {
render(<RegistrationForm />);
await userEvent.type(screen.getByLabelText(/email/i), 'test@example.com');
await userEvent.type(screen.getByLabelText(/password/i), 'password123');
await userEvent.click(screen.getByRole('button', { name: /submit/i }));
expect(await screen.findByText(/registration successful/i)).toBeInTheDocument();
});

A celestial landscape with floating geometric crystals in bright sky blue and mustard yellow colors featuring abstract planetary forms high-quality ultra-realistic cinematic 8K UHD sharp and detailed

Remember, good tests should be:

  • Easy to maintain
  • Quick to run
  • Reliable and deterministic
  • Focused on behavior, not implementation

By following these best practices, you’ll create a robust test suite that catches bugs early and makes refactoring safer and easier.

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.