Mid From PDF React React.js

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.

More from React.js Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details