Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
React Test Example 
2.1.
Program
2.2.
Program
2.3.
Output
2.4.
Program 
2.5.
Output 
3.
User Generated Events Example
3.1.
Program
3.2.
Program
3.3.
Output
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

React Testing Library Implementation

Introduction

React Testing Library(RTL) is a react component testing tool that is highly functional and useful for unit testing and QA. To learn more about the React Testing Library and its setup, check out Testing React App with Jest and React Testing Library Setup

This article will explore the implementation of the React Testing Library with the Jest Testing framework in JavaScript with some examples. This article requires basic knowledge of the Jest framework. So if you are not familiar with Jest, check out our introductory articles Getting Started with Jest and Writing your first Unit Test with Jest.

React Test Example 

There are two methods of implementing a React test using Jest and React Testing Library. 

  • You can use the Create React App(CRA) to create a react application. The React app you create with CRA will already include Jest and React Testing Library, so you can start testing immediately.
npx create-react-app test-example
  • You can also implement the React Testing Library without CRA. In that case, you will need to install Jest and React Testing Library manually in your node project using NPM.
npm install --save-dev @testing-library/react jest

In this article, we will use the default template of CRA to create a new React application. The React app(test-example) that you will make using the command above will already include App.js and App.test.js inside the src folder with the following content.

Program

// src/App.js
import logo from './logo.svg';
import './App.css';

function App() {
 return (
   <div className="App">
     <header className="App-header">
       <img src={logo} className="App-logo" alt="logo" />
       <p>
         Edit <code>src/App.js</code> and save to reload.
       </p>
       <a
         className="App-link"
         href="https://reactjs.org"
         target="_blank"
         rel="noopener noreferrer"
       >
         Learn React
       </a>
     </header>
   </div>
 );
}

export default App;

Program

// src/App.test.js
import { render, screen } from "@testing-library/react";
import App from "./App";

test("renders learn react link", () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

 

The App.test.js file uses the render method from React Testing Library to render the App component from App.js virtually and append it to the document.body. 

We access the rendered HTML through the screen object. The screen object also has DOM testing methods bound into it. That's why the above test code is using screen.getByText() to query the anchor <a> element by its textContent value.

The test finally asserts if the link element is available in the document object with Jest’s expect method.

You can run the test using the npm run test inside your app from the command line.

Output

You can also see the output of the render() call by using the screen.debug() method after it. That will render the whole document.body in your console log when you run the test.

Program 

test("renders learn react link", () => {
  render(<App />);
  screen.debug();
  ...
});

Output 

User Generated Events Example

You can use React Testing Library to test user-generated events like button clicking, typing values in the text box, etc. 

We will use an example that tests a React Application with a button component that toggles between Light and Dark themes. The code for that application looks something like this.

Program

// src/App.test.js
import React, { useState } from "react";

function App() {
  const [theme, setTheme] = useState("light");

  const toggleTheme = () => {
     const nextTheme = theme === "light" ? "dark" : "light";
     setTheme(nextTheme);
  };

  return <button onClick={toggleTheme}>Current theme: {theme}</button>;
}

export default App;

Now we can write a test code for our application. Here we use the user-event library, a companion library of RTL which simulates user-browser interaction. The library has several methods like dblClick for double-clicking an element and type for typing into a textbox.

We can use the userEvent.click() method to find our button element and simulate a click event. After simulating the click, the text asserts a success by inspecting if the button element text contains "dark."

Program

// src/App.test.js
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import App from "./App";

test("Test theme button toggle", () => {
  render(<App />);
  const buttonEl = screen.getByText(/Current theme/i);

  userEvent.click(buttonEl);
  expect(buttonEl).toHaveTextContent(/dark/i);
});

Output

Frequently Asked Questions

  1. What is the React testing library?
    React Testing Library(RTL) is a lightweight tool that you can use to test react components. RTL works by providing light utility functions on top of react-dom and react-dom/test-utils, encouraging better testing practices.

     
  2. Why do we need the React Testing Library?
    The React Testing Library provides a set of helpers that lets you test React components without relying on the details of their implementation. Using RTL makes refactoring simple and also pushes you towards better accessibility practices.

     
  3. What is npm in React?
    NPM, or Node Package Manager, is an online directory that contains multiple registered open-source packages. NPM modules include various functions as a third-party package when installing it into an app using the npm install command.

     
  4. What is React?
    React is a JavaScript library that we can utilize to build user interfaces. It deals with the views and lets us choose the rest of our front-end architecture. However, a substantial library ecosystem is developed around it, allowing us to build a complete framework around React by adding a few libraries.

Conclusion

In this article, we have extensively discussed the implementation of the React Testing Library in Javascript using Jest with the help of examples. There is a lot more for you to explore in RTL. You can try exploring this library using different test cases, testing frameworks, and versions to better grip this topic.

We hope that this blog has helped you enhance your knowledge regarding React Testing Library, and if you would like to learn more, check out our articles on React Test UtilitiesReact Test Renderer, and Testing React App with Jest. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass