React Testing Library - современное руководство по тестированию в React

React Testing Library

React Testing Library is a library for testing React components that helps developers create and maintain reliable and understandable tests. It was created with the philosophy of "testing the patient as the user interacts".

The main goal of React Testing Library is to simulate user actions and verify the expected behavior of components when interacting with them. It differs from other libraries such as Enzyme or react-test-renderer in that it focuses on testing the end result and does not care about the internal implementation of the component. This allows tests to be more resilient to changes in the internal logic of the component and makes them more similar to real user interaction.

To get started with React Testing Library, you will need to install it using npm or yarn:

npm install --save-dev @testing-library/react

or

yarn add --dev @testing-library/react

After successful installation, you can import the necessary methods and components from the library:

import { render, screen } from '@testing-library/react';
import App from './App';

In this example, we render the App component and find the element with the test id 'app'. Then we check whether this element is in the document.

React Testing Library provides many useful methods for finding elements based on their role, label, text, and other criteria. It also includes methods for simulating user actions such as clicks, inputs, and form submissions.

Here are a few more examples of using React Testing Library:

import { render, fireEvent, screen } from '@testing-library/react';
import Button from './Button';
test('button click changes text', () => {
render(<Button />);
const buttonElement = screen.getByRole('button');
const textElement = screen.getByText('Initial Text');
fireEvent.click(buttonElement);
expect(textElement).toHaveTextContent('Changed Text');
});
test('validates form input', () => {
render(<Form />);
const inputElement = screen.getByLabelText('Username');
const submitButton = screen.getByRole('button', { name: 'Submit' });
fireEvent.change(inputElement, { target: { value: 'test_user' } });
fireEvent.click(submitButton);
const errorElement = screen.getByText('Username must be at least 5 characters');
expect(errorElement).toBeInTheDocument();
});

In the first example, we render the Button component, click on the button, and check that the text element has changed. In the second example, we render the Form component, enter a value in the input field, and click the submit button. Then we check that the element with the error message is displayed in the document.

React Testing Library also supports asynchronous testing, mocks, and additional features to improve performance and ease of writing tests. You can find more information in the official React Testing Library documentation.

Using React Testing Library helps developers create reliable tests that continue to work even when the internal implementation of the component changes. It also contributes to the development of more accessible code, as tests are based on user actions.

Похожие вопросы на: "react testing library "

Python Tuple: основные принципы и возможности
<h1>Использование метода QuerySelector для работы с элементами в JavaScript
Doctype HTML: основа современной веб-разработки
DOCc - всё для вашей документации
Изучение языка программирования C# с Byte
Использование метода QuerySelectorAll в JavaScript
msedge.exe: основной файл браузера Microsoft Edge
Visual Studio 2017 Community: бесплатная мощная среда разработки
Символы в JavaScript
SQL IIF - условное выражение в SQL запросах