Skip to content
Announcing the new Pro Zone. Check it out!

React Testing Tutorial – How to Test React Components

The two main tools you need to test your React components are:

  1. A test runner tool
  2. A React component testing tool

But what exactly is the difference between a test runner and a React component testing tool? Let’s find out.

Test Runner vs. React Component Testing Tool: What’s the Difference?

Below are the differences between a test runner and a React component testing tool.

Test runner: What does it mean?

A test runner is a tool developers use to run a test script and print the test’s results on the command line (CLI).

For instance, suppose you need to run the test cases in your project’s App.test.js test script. In such a case, you will use a test runner.

The test runner will execute App.test.js and print the test’s results on the command line.

Typical examples of test runners are Jasmine, Mocha, Tape, and Jest.

Let’s now discuss what a React component testing tool is.

React component testing tool: What does it mean?

A React component testing tool provides helpful APIs for defining a component’s test cases.

For instance, suppose you need to test your project’s <App /> component. In such a case, you will use a React component testing tool to define the component’s test cases.

In other words, a React component testing tool provides the APIs for writing your component’s test cases.

Typical examples are Enzyme and the React Testing Library.

So, now that we know what a test runner and React component testing tool are, let’s use a mini-project to understand how React testing works.

Project: How React Testing Works

In the following steps, we will use Jest and the React Testing Library (by Kent C. Dodds) to learn how React testing works.

Prerequisite

To complete this tutorial, you need to know how to use Jest. See the TDD tutorial for a good guide on Jest.

Step 1: Get the right Node and NPM version

Make sure that you have Node 10.16 (or greater) and NPM 5.6 (or greater) installed on your system.

If you prefer to use Yarn, ensure you have Yarn 0.25 (or greater).

Step 2: Create a new React app

Use NPM’s create-react-app package to create a new React app called react-testing-project.

Terminal window
npx create-react-app react-testing-project

Alternatively, you can use Yarn to configure your project like so:

Terminal window
yarn create react-app react-testing-project

Step 3: Go inside the project directory

After the installation process, navigate into the project directory like so:

Terminal window
cd react-testing-project

Step 4: Set up your test environment

Install the following test packages:

  • jest
  • @testing-library/react
  • @testing-library/jest-dom
  • @testing-library/user-event

Now, let’s discuss the purpose of each of the above test packages.

jest

jest is the test runner tool we will use to run this project’s test scripts and print the test results on the command line.

@testing-library/react

@testing-library/react is the React Testing Library which gives you the APIs you need to write test cases for your React components.

@testing-library/jest-dom

@testing-library/jest-dom provides some set of custom jest matchers for testing the DOM’s state.

@testing-library/user-event

@testing-library/user-event provides the userEvent API for simulating users’ interaction with your app on a web page.

Step 5: Clean up the src folder

Delete all files inside the project directory’s src folder.

Step 6: Create your code files

Create the following files inside your project’s src folder.

  • index.js
  • App.js
  • App.test.js

Step 7: Render the App component

Open your index.js file and render the App component to the DOM like so:

index.js
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
// Render the App component into the root DOM
createRoot(document.getElementById("root")).render(<App />);

Step 8: Write your test case

Suppose you want your App.js file to render a <h1>CodeSweetly Test</h1> element to the web page. In that case, open your test script and write a test code specifying the result you expect your <App /> component to produce.

Here’s an example:

App.test.js
import React from "react";
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import App from "./App";
test("codesweetly test heading", () => {
render(<App />);
expect(screen.getByRole("heading")).toHaveTextContent(/codesweetly test/i);
});

Here are the main things we did in the test snippet above:

  1. We imported the packages needed to write our test case.
  2. We wrote a test case specifying that we expect our <App /> component to render a heading element with a "codesweetly test" text.

Keep in mind that there are three alternative ways to write the above expect statement:

// 1. Using jest-dom's toHaveTextContent() method:
expect(screen.getByRole("heading")).toHaveTextContent(/codesweetly test/i);
// 2. Using the heading's textContent property and Jest's toMatch() method:
expect(screen.getByRole("heading").textContent).toMatch(/codesweetly test/i);
// 3. Using React Testing Library's name option and jest-dom's toBeInTheDocument() method
expect(
screen.getByRole("heading", { name: /codesweetly test/i }),
).toBeInTheDocument();

Suppose you run the test code now. The test will fail because you’ve not developed the component for which you created the test. So, let’s do that now.

Step 9: Develop your React component

Open your App.js file and develop the component to pass the prewritten test.

Here’s an example:

App.js
import React from "react";
const App = () => <h1>CodeSweetly Test</h1>;
export default App;

The App component, in the snippet above, renders a <h1> element containing a "CodeSweetly Test" text.

Step 10: Run the test

Run the prewritten test to check if your program passed or failed.

Terminal window
npm test App.test.js

Once you’ve initiated the test, Jest will print a pass or fail message on your editor’s console. The message will look similar to this:

Terminal window
$ jest
PASS src/App.test.js
codesweetly test heading (59 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.146 s
Ran all test suites related to changed files.

Step 11: Run the application

Take a look at your app in the browser by running:

Terminal window
npm run start

Once you run the command above, your app will automatically open on your default browser.

Step 12: Refactor the test code

Suppose you wish to change the heading’s text when users click a button. In that case, you can simulate users’ interaction with the button to confirm that it works as intended.

Here’s an example:

App.test.js
import React from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import App from "./App";
describe("App component", () => {
test("codesweetly test heading", () => {
render(<App />);
expect(screen.getByRole("heading")).toHaveTextContent(/codesweetly test/i);
});
test("a codesweetly project heading", () => {
render(<App />);
const button = screen.getByRole("button", { name: "Update Heading" });
userEvent.click(button);
expect(screen.getByRole("heading")).toHaveTextContent(
/a codesweetly project/i,
);
});
});

Here are the main things we did in the test snippet above:

  1. We imported the packages needed to write our test case.
  2. We wrote a test case specifying that we expect the <App /> component to render a heading element with a "codesweetly test" text.
  3. We wrote another test case simulating users’ interaction with the app’s button element. In other words, we specified that whenever a user clicks the button, we expect <App />’s heading to update to "a codesweetly project" text.

Step 13: Refactor your React component

So, now that you’ve refactored your test code, let’s do the same for the App component.

App.js
import React, { useState } from "react";
const App = () => {
const [heading, setHeading] = useState("CodeSweetly Test");
const handleClick = () => {
setHeading("A CodeSweetly Project");
};
return (
<>
<h1>{heading}</h1>
<button type="button" onClick={handleClick}>
Update Heading
</button>
</>
);
};
export default App;

Here are the main things we did in the snippet above:

  1. App’s heading state got initialized with a "CodeSweetly Test" string.
  2. We programmed a handleClick function to update the heading state.
  3. We rendered a <h1> and <button> elements to the DOM.

Note the following:

  • <h1>’s content is the heading state’s current value.
  • Whenever a user clicks the button element, the onClick() event listener will trigger the handleClick() function. And handleClick will update App’s heading state to "A CodeSweetly Project". Therefore, <h1>’s content will also change to "A CodeSweetly Project".

Step 14: Rerun the test

Once you’ve refactored your component, rerun the test (or check the actively running test) to confirm that your app still works as expected.

Afterward, check the browser to see your recent updates.

And that’s it!

Congratulations! You’ve successfully used Jest and the React Testing Library to test a React component.🎉

Useful Resources