Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React Testing Library

1. Introduction

React Testing Library (RTL) is a lightweight testing library for testing React components. It encourages testing from a user’s perspective, focusing on how components behave rather than their internal implementation.

2. Installation

To install React Testing Library, run the following command in your project directory:

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

3. Key Concepts

  • Queries: RTL provides various methods to query elements, such as getByText, getByRole, etc.
  • Rendering: Use render to render components into a virtual DOM for testing.
  • User Events: Use user-event to simulate user interactions.

4. Testing Components

4.1 Basic Example

Here's a simple example of testing a React component:

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

test('renders MyComponent', () => {
    render();
    const linkElement = screen.getByText(/learn react/i);
    expect(linkElement).toBeInTheDocument();
});

4.2 Simulating User Events

To test user interactions, you can utilize the user-event library:

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import ButtonComponent from './ButtonComponent';

test('button changes text on click', () => {
    render();
    const button = screen.getByRole('button');
    userEvent.click(button);
    expect(button).toHaveTextContent(/clicked/i);
});

5. Best Practices

  • Test behavior, not implementation details.
  • Use descriptive test names.
  • Keep tests isolated and independent.
  • Avoid using waitFor unless necessary.

6. FAQ

What is the difference between React Testing Library and Enzyme?

RTL focuses on testing components from the user's perspective, while Enzyme provides more granular control over component state and lifecycle.

Can I test asynchronous code with React Testing Library?

Yes, you can use waitFor and findBy queries to handle asynchronous tests.