Understanding React Testing Library (RTL) and Jest

Photo by CDC on Unsplash

Understanding React Testing Library (RTL) and Jest

·

3 min read

React Testing Library (RTL) is a specialized unit testing library designed specifically for React applications. The goal of the library is to assist developers create tests that resemble user interactions with the application. By doing so, RTL promotes a testing approach that mirrors real-world usage scenarios.

The Importance of Testing

Testing is a crucial aspect of software development, serving multiple purposes beyond mere bug identification. Thoroughly tested software ensures reliable, quality, and high-performance software operation. Several reasons underscore the significance of testing:

  • Cost-Efficiency: Identifying and fixing bugs during the early development phases significantly reduces the cost associated with addressing issues after deployment.

  • Security: Rigorous testing instills confidence in clients by providing a more reliable product, improving security, and minimizing unforeseen issues.

What is Jest?

Jest is a test runner that locates tests, executes them, and determines whether the tests pass or fail. Additionally, Jest provides functionality for organizing tests into suites, defining test cases, and making assertions.

Analyzing an Example

1 import { render, screen } from "@testing-library/react";
2 import App from "./App";
3
4 // start of test block
5 test('renders learn react link', () => {
6  render(<App />);
7   const linkElement = screen.getByText(/learn react/i);
8   expect(linkElement).toBeInTheDocument();
9 });
10 // end of test block
  • line 1: imports necessary functions from RTL for rendering and accessing components.

    • screen looks at the component we rendered. It contains multiple methods that allow us to get certain elements we want from the component that we rendered
  • line 5: describes what the test block is testing for, then calls a callback function that contains the test to be executed

  • line 6: specifies which component to render for testing (tip: make sure to import that component first as seen in line 2)

  • line 7: specifies which elements within the specified component to interact with for testing. In this example, we are targeting the link element with the "learn react" text

  • line 8: assert that the results are as expected. In this example, we expect the link to be in the document

Screen Shot 2022-09-06 at 6.01.07 PM.png

note: 90% of the time you'll be using the .getBy methods

Priorities

RTL emphasizes making tests accessible and uses various methods based on priorities:

Accessible to Everyone:

  • .getByRole: Identifies elements by their role (heading, button, etc.).

  • .getByLabelText: Targets form elements.

  • .getByPlaceholderText.

  • .getByText: Searches for elements by their text content.

Semantic Queries (read by screen readers)

  • .getByAltText

  • .getByTitle

Test ID

  • .getByTestId - last resort if none of the above can target the element needed to test

Describe Block

The describe block groups and organizes common tests. The describe function takes two parameters: a string describing the group of tests and a callback function containing the actual test cases

describe('Math operations', () => {
  test('should add two numbers', () => {
    // Test logic for addition
  });

  test('should subtract two numbers', () => {
    // Test logic for subtraction
  });

  test('should multiply two numbers', () => {
    // Test logic for multiplication
  });
});

Assertions

Assertions are statements that verify whether test conditions are met. If these conditions are met, tests pass. If these conditions aren't met, the tests will fail. Some of the most popular are as follows:

Best practices

When testing in Jest, there are best practices that ensure your tests are reliable, effective, and maintainable.

  • Organize tests with descriptive describe blocks

  • Use test or it to define tests

  • Arrange, act, assert

  • Mock dependencies and external services

  • Avoid global state changes

  • Use matchers appropriately