javascript / beginner
Snippet
Simulating Button Clicks with React Testing Library
React Testing Library allows developers to simulate user interactions on rendered components. By using a mock function with jest.fn() and triggering events with fireEvent.click, you can test that event handlers are called as expected when users click a button.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { render, screen, fireEvent } from '@testing-library/react';import CounterButton from './CounterButton';test('calls onClick handler when clicked', () => {const handleClick = jest.fn();render(<CounterButton onClick={handleClick} label="Increment" />);const buttonElement = screen.getByRole('button', { name: /increment/i });fireEvent.click(buttonElement);expect(handleClick).toHaveBeenCalledTimes(1);});
react
Breakdown
1
const handleClick = jest.fn();
Creates a Jest mock function to track if and how many times it was called.
2
render(<CounterButton onClick={handleClick} label="Increment" />);
Renders the component into a virtual DOM container for testing.
3
const buttonElement = screen.getByRole('button', { name: /increment/i });
Finds the rendered button element accessible by its accessible role and text label.
4
fireEvent.click(buttonElement);
Dispatches a DOM click event on the target button element.
5
expect(handleClick).toHaveBeenCalledTimes(1);
Asserts that the mock function was executed exactly once as a result of the click.