How do you test component interactions and events?
To test component interactions like button clicks, form submissions, or other events, you
can use fireEvent or user-event (for more realistic user interactions).
Example using fireEvent:
import { render, screen, fireEvent } from '@testing-library/react';
import MyComponent from './MyComponent';
test('button click changes text', () => {
render(<MyComponent />);
const button = screen.getByText('Click me');
fireEvent.click(button);
expect(screen.getByText('You clicked!')).toBeInTheDocument();
});
Example using user-event (better for simulating real user interactions):
npm install --save-dev @testing-library/user-event
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import MyComponent from './MyComponent';
test('button click changes text', () => {
render(<MyComponent />);
const button = screen.getByText('Click me');
userEvent.click(button);
expect(screen.getByText('You clicked!')).toBeInTheDocument();
});
user-event is better because it simulates real user actions like clicks, typing, and more.