Introducing React Testing Library

Mragang Jain
Airtel Digital
Published in
6 min readOct 2, 2023

In the fast-paced world of telecommunications, Airtel stands tall as a global leader, connecting millions across continents. With an unwavering commitment to providing top-notch services, Airtel ensures that its software applications are not just cutting-edge but also impeccable in performance and reliability.

Importance of Quality Assurance and Testing:

Quality assurance and testing are the bedrock of software development, and they play an indispensable role in Airtel’s commitment to excellence. In an industry where a single glitch can disrupt communication for thousands, rigorous testing is not a luxury but a necessity. It ensures that Airtel’s digital solutions are robust, secure, and meet the highest standards of quality.

In this blog post, we delve into Airtel’s journey of ensuring the quality and reliability of its React applications by leveraging the power of React Testing Library. We will explore how React Testing Library has become an indispensable tool in Airtel’s codebase, empowering developers to write effective tests for React components.

By the end of this post, you will gain insights into how Airtel employs React Testing Library to enhance the user experience, maintain customer trust, and elevate the quality of its software applications.

What is React Testing Library?

The React Testing Library is a lightweight and highly effective solution designed for testing React components. Unlike some testing frameworks that require dealing with instances of rendered React components, it takes a different approach. Its primary guiding principle is:

The more your tests resemble the way your software is used, the more confidence they can give you.

This fundamental principle underscores the library’s philosophy, emphasizing that testing should closely mirror how real users interact with the application. Instead of manipulating internal React component instances, React Testing Library encourages working directly with the actual DOM nodes that the components render. This approach provides a more accurate representation of how users interact with the application.

Why do we need testing?

For developers who are not familiar with testing before, testing is a very important step that helps you to check & verify problems before deploying your application to end users on production.

While writing testing for functionalities, we could be able to see which logic is missing and correct it accordingly. More importantly, when other developers take care of your code, they could be able to extend/modify the logic without breaking the existing logic, or at least they are aware of those changes to update the test cases.

Install React testing library dependencies
To install React Testing Library (RTL) dependencies as development dependencies in Create React App (CRA) applications, which come with a default basic configuration, use the following command for Webpack.

// Install React Testing Library
npm install --save-dev @testing-library/react
// Install Jest
npm install --save-dev jest
npm install --save-dev jest-environment-jsdom
  • @testing-library/react: the core dependency that install react testing library.
  • jest: the core dependency required for Jest to work. Jest is a popular JavaScript testing framework that is widely used for testing JavaScript applications

Adding Jest Configuration

Adding testing scripts
in the package.json in the script object add the following scripts

scripts:{
... //scripts you already have
test: "jest",
coverage: "jest --coverage"
}

test: "jest": Identify which of the tests are passing and failing to determine their status accurately.
coverage: "jest --coverage": will run our tests too and also collect our coverage.

Test Structure:

We follow a structured approach to organize tests. We typically create a dedicated folder for tests (e.g., __tests__) and organize test files to mirror the structure of the components for what we are testing.

We write test cases that cover a range of scenarios, including component rendering, user interactions, and expected behavior. Here are some examples:

Rendering Test:

// Example: Testing the rendering of a basic component
test('renders a button component', () => {
render(<Button label="Click me" />);
const buttonElement = screen.getByText('Click me');
expect(buttonElement).toBeInTheDocument();
});

Interaction Test:

// Example: Testing a button click event
test('clicking the button triggers an action', () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick} />);
const buttonElement = screen.getByRole('button');

userEvent.click(buttonElement);
expect(handleClick).toHaveBeenCalledTimes(1);
});

Behavior Test:

// Example: Testing a component's behavior based on props
test('displays an error message when the error prop is true', () => {
render(<ErrorMessage error={true} message="An error occurred" />);
const errorMessageElement = screen.getByText('An error occurred');
expect(errorMessageElement).toBeInTheDocument();
});

Best Practices:

  • We follow the principle of writing tests that resemble real user interactions to increase confidence in the application’s behavior.
  • We avoid relying on component implementation details, preferring to query the DOM as a user would.
  • Tests are kept focused, covering specific aspects of a component’s behavior, making them easier to maintain.
  • Mocking dependencies helps create isolated tests, reducing the risk of false positives/negatives.
  • Regularly reviewing and updating tests ensures they stay in sync with evolving code and requirements.

At Airtel, handling API calls within React components during testing is a critical aspect of ensuring the reliability and efficiency of their tests. To achieve this, We employ techniques and libraries for mocking API responses, creating controlled environments for testing without relying on actual external services.

Using Jest’s Built-in Mocking:

// Assuming a function fetchData that makes an API call using Axios
import axios from 'axios';

// Mocking the Axios request
jest.mock('axios');

test('fetches data successfully', async () => {
// Mocking a successful API response
axios.get.mockResolvedValue({ data: { someData: 'value' } });

// Your component or function that makes the API call
const data = await fetchData();

// Assertions based on the mocked response
expect(data.someData).toEqual('value');
});

Let’s create App.js component and display Hello World on UI

Write your test Create a test file for your component. By convention, test files should be named with the .test.js extension and placed alongside the component file. Create a App.test.js file with the following content:

Run your tests using the npm run testcommand in the terminal. Jest will automatically detect and execute the test files.

Let’s see few example for mocking the hook’s

  • useNavigate Hook
  • useState Hook
  • useEffect Hook

Conclusion

React Testing Library plays a pivotal role in Airtel’s commitment to delivering robust user interfaces. By adhering to its principles, Airtel ensures that their applications behave as expected from the end user’s perspective. This approach not only fosters higher confidence in the reliability of their software but also enhances the user experience.

We trust that this blog post has illuminated the significance of the React Testing Library (RTL) when it comes to React applications. By integrating RTL into your projects, you can certainly enhance your code’s performance and organization. This, in turn, simplifies the scalability and long-term maintenance of your applications, making them more robust and reliable.

Thanks for reading! ⭐️

--

--

Mragang Jain
Airtel Digital

A frontend developer who love designing web applications.