ProCodebaseProCodebase
  • ModusA Growth OS for your business, on WhatsAppKiosqSell more. Chase less.AI InterviewerAutomated screening & AI-led interviewsXperto AIAI prep companion for candidatesAI Tools HubResume builder, learning paths & more
  • Pre-Vetted DevelopersScreened, scored and ready to interviewAI-Native DevelopersSenior engineers on an hourly basis
  • Services
  • Features
  • Jobs
  • FAQs
Sign inBook a demo
  • Services
  • Features
  • Jobs
  • FAQs
Sign inBook a demo
ProCodebaseProCodebase

ProCodebase Technologies builds AI products for hiring and growth, and ships software for clients as a technical consultancy. We source, screen and deliver pre-vetted developers — so you only interview high-signal candidates.

Products

  • Modus
  • Kiosq
  • AI Interviewer
  • Xperto AI
  • AI Tools Hub

Hire & build

  • Pre-Vetted Developers
  • AI-Native Developers
  • Technical Consultancy
  • MVP Development
  • Features

Resources

  • Articles
  • Topics
  • Certifications
  • Collections
  • Jobs

Company

  • About Us
  • Contact Us
  • Book a Demo
  • FAQs

© 2026 ProCodebase Technologies. All rights reserved.

  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Testing React Components with Jest and React Testing Library

author
Generated by
Abhishek Goyan

24/08/2024

React

Sign in to read full article

Testing is an essential part of the software development process as it helps identify bugs and ensures that the application behaves as expected. In the React ecosystem, two popular libraries stand out for testing components: Jest and React Testing Library. In this post, we’ll dive into these tools, their significance, and demonstrate how to utilize them with a practical example.

Why Test React Components?

Testing React components can:

  1. Catch Errors Early: By writing tests, you can catch bugs before they make it to production.
  2. Ensure Component behavior: Tests can verify that components render the right content based on the props they receive.
  3. Facilitate Changes: When you refactor your code, having tests makes it safer to touch the codebase since you can easily validate your changes.

Getting Started with Jest and React Testing Library

1. Setting Up Your Environment

To begin, you need to have a React app setup. If you haven’t created one, you can create a new React app using Create React App:

npx create-react-app my-app cd my-app

By default, Create React App comes with Jest as the test runner. To add React Testing Library, you can install it using npm:

npm install --save-dev @testing-library/react

2. Simple Component Example

Let’s create a simple component that we will test. This component will display a greeting message based on the received name prop.

// src/Greeting.js import React from 'react'; const Greeting = ({ name }) => { return ( <div> <h1>Hello, {name}!</h1> </div> ); }; export default Greeting;

3. Writing Tests

Now that we have our Greeting component, let’s write tests for it. Create a new file named Greeting.test.js in the same directory as your component.

// src/Greeting.test.js import React from 'react'; import { render, screen } from '@testing-library/react'; import Greeting from './Greeting'; test('renders the greeting message', () => { render(<Greeting name="John" />); const greetingElement = screen.getByText(/hello, john!/i); expect(greetingElement).toBeInTheDocument(); });

Breakdown of the Test

  1. Import Necessary Modules: We import React, the render and screen functions from React Testing Library, and our Greeting component.

  2. The Test Function: We define a test case using test. The first argument is a description of what we're testing, and the second argument is a function that contains our test logic.

  3. Render the Component: We use the render method to render our Greeting component with the name prop set to "John".

  4. Query for the Element: We utilize screen.getByText to query the rendered output for the text "Hello, John!". The /i makes the regex case-insensitive so it will match "hello" as well.

  5. Assertion: Finally, we assert that the greeting element is present in the document using expect.

4. Running the Tests

To run your tests, simply execute the following command in your terminal:

npm test

This will trigger Jest to find and execute your test files. You should see output indicating whether your tests passed or failed.

5. Adding More Tests

You can expand your tests to cover various scenarios, such as showing a default greeting or handling missing props. For example:

test('renders default greeting when name is not provided', () => { render(<Greeting />); const defaultGreetingElement = screen.getByText(/hello, !/i); expect(defaultGreetingElement).toBeInTheDocument(); });

In this test, the component will need a slight adjustment to handle the default case:

const Greeting = ({ name = '' }) => { return ( <div> <h1>Hello, {name}!</h1> </div> ); };

This way, if no name prop is provided, the component will default to an empty string.

Additional Features of React Testing Library

React Testing Library encourages good testing practices. It encourages you to test your components the way a user would interact with them, rather than focusing on implementation details.

You can also test for events such as clicks, form submissions, and other user interactions using built-in functions:

import userEvent from '@testing-library/user-event'; // Inside your test case userEvent.click(buttonElement);

This promotes testing the user experience rather than the internal workings of your components.

Mocking and Asynchronous Tests

When testing components that fetch data or have asynchronous behavior, you can use Jest to mock API calls and manage async operations effectively. This enables you to isolate your components and test them in various states.

For instance, you might want to mock a function or use libraries like msw (Mock Service Worker) for handling API requests to ensure your tests remain fast and consistent.

By keeping the separation of concerns, Jest and React Testing Library enable you to write robust and maintainable tests for your React components.

Popular tags

ReactJestReact Testing Library

Share now!

Like & bookmark

Related collections

  • Mastering React Concepts

    24/08/2024 · ReactJS

  • React Interview Challenges: Essential Coding Problems

    14/09/2024 · ReactJS

Related articles

  • Understanding Advanced Promises in JavaScript

    20/09/2024 · ReactJS

  • Styling React Components: CSS Styled-Components

    24/08/2024 · ReactJS

  • Understanding React Suspense

    16/07/2024 · ReactJS

  • Getting Started with React Storybook and Cypress

    03/09/2024 · ReactJS

  • Understand Hooks in React JS

    25/07/2024 · ReactJS

  • Building a Pagination Component in React

    14/09/2024 · ReactJS

  • Lists and Keys: Rendering Multiple Items in React

    24/08/2024 · ReactJS

Popular category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design