Testing w/ React Testing Library + Jest

Photo by CDC on Unsplash

Testing w/ React Testing Library + Jest

Aug 19, 2022·

2 min read

What is React Testing Library (RTL)?

React Testing Library, referred to going forward as RTL, is a type of unit test specifically for React applications. The goal of the library is to help you write tests that resemble how a user would use your application.

Why do we test?

Testing ensures a product or application performs the way it is intended. Testing is important for discovering defects/bugs before the delivery to the client. Thoroughly tested software ensures reliable, quality, and high-performance software operation. Additional reasons to test are as follows:

  • saves the company money: in case you find any bugs in the early phases, fixing them costs a reduced amount of money.
  • security: the more test a specified product undergoes, the more reliable a product a client can expect.

What is Jest?

Jest is a test runner that finds tests, runs the tests, and determines whether the tests passed or failed. Additionally, Jest offers functions for test suites, test cases, and assertions.

The anatomy of a RTL test block

1 import { render, screen } from "@testing-library/react";
2 import App from "./App";
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

Anatomy breakdown

  • line 1
    • 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 the purpose of this test. 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


accessible to everyone

  • .getByRole - the role of the element (heading, button, etc)
  • .getByLabelText - for forms
  • .getByPlaceholderText
  • .getByTet

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.

Best practices