The React Testing Library (RTL) is a popular testing utility for React applications. Here’s a cheat sheet to help you use React Testing Library effectively:
Installation
Install Dependencies:
npm install --save-dev @testing-library/react @testing-library/jest-dom
Basic Usage
Render Component:
import { render } from '@testing-library/react';
const { getByText } = render(<Component />);
Query Elements:
- Use
getBy
,queryBy
,findBy
to get elements by text, role, label, etc.
Assertions:
- Use Jest matchers for assertions.
expect(getByText('Hello')).toBeInTheDocument();
Queries
getByText:
- Find an element with text content.
getByText('Hello');
getByRole:
- Find an element by its role.
getByRole('button');
getByTestId:
- Find an element by a data-testid attribute.
getByTestId('my-element');
Async Operations
waitFor:
- Wait for an element to appear.
await waitFor(() => getByText('Loaded'));
findBy:
- Find an element asynchronously.
const element = await findByText('Async Content');
User Events
userEvent:
- Simulate user events.
import userEvent from '@testing-library/user-event';
userEvent.click(button);
fireEvent:
- Use fireEvent for custom events.
fireEvent.change(input, { target: { value: 'New Value' } });
Testing Forms
Form Submission:
- Simulate form submission.
fireEvent.submit(form);
Input Change:
- Test input changes.
fireEvent.change(input, { target: { value: 'new value' } });
Mocking
jest.mock:
- Mock modules and functions.
jest.mock('axios');
jest.fn:
- Create mock functions.
const mockFn = jest.fn();
Cleanup
cleanup:
- Clean up after each test.
import { cleanup } from '@testing-library/react';
afterEach(cleanup);
beforeEach/afterEach:
- Run setup and cleanup before/after each test.
beforeEach(() => setup());
afterEach(() => cleanup());
Snapshot Testing
toMatchSnapshot:
- Use Jest snapshots for UI component testing.
expect(container).toMatchSnapshot();
Additional Tips
- Debugging:
- Use
debug()
to log the current state of the DOM.
- Use
const { debug } = render(<Component />);
debug();
- Docs and Resources:
- Refer to the official documentation for more details.
This cheat sheet covers some common scenarios in testing React components with React Testing Library. Remember to adapt these examples based on your specific testing needs and application structure.