javascript / beginner
Snippet
Simulating Button Click Interactions with User Event in Unit Tests
Using React Testing Library alongside userEvent allows you to test component interactivity in an automated test environment. It simulates genuine user clicks and verifies that the UI updates accordingly.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import Counter from './Counter';test('increments counter on button click', async () => {render(<Counter />);const button = screen.getByRole('button', { name: /increment/i });await userEvent.click(button);expect(screen.getByText(/count: 1/i)).toBeInTheDocument();});
react
Breakdown
1
render(<Counter />);
Mounts the Counter component into a virtual DOM container for testing.
2
const button = screen.getByRole('button', { name: /increment/i });
Queries the rendered document for an accessible button matching the accessible name.
3
await userEvent.click(button);
Simulates an asynchronous user click event on the found button element.
4
expect(screen.getByText(/count: 1/i)).toBeInTheDocument();
Asserts that the updated counter text is now visible in the DOM.