Testing React Components

Learn to implement tests on the different components in React frontend.

We are going to implement tests on the Page, Question, and HomePage components. React component tests can be challenging because they have dependencies, such as the browser's DOM and sometimes HTTP requests. Due to this, we are going to leverage the React Testing Library and Jest’s mocking functionality to help us implement our tests.

Testing the Page component

Carry out the following steps to test that the Page component renders correctly:
1. Create a file for the tests called Page.test.tsx with the following content:

Press + to interact
import React from 'react';
import { render, cleanup } from '@testing-library/react';
import { Page } from './Page';
test('When the Page component is rendered, it should
contain the correct title and content', () => {
});

We imported React with our Page component, along with some useful functions from the React Testing Library.

The React Testing Library was installed by Create React App when we created the frontend project. This library will help us select elements that we want to check, without using internal implementation details such as element IDs or CSS class names.

2. Let's render the Page component in the test by adding the following highlighted lines of code:

Press + to interact
test('When the Page component is rendered, it should
contain the correct title and content', () => {
const { queryByText } = render(
<Page title="Title test">
<span>Test content</span>
</Page>,
);
});

We use the render function from React Testing Library to render the Page component by passing in JSX.

The render function returns various useful items. One of these items is the queryByText ...