Firing events in tests
The React Testing Library provides a fireEvent()
method that can be used to fire DOM events in your test cases. The fireEvent()
method is used in the following way. First, we have to import it from the React Testing Library:
import { render, screen, fireEvent } from '@testing-library/react';
Next, we have to find the element and trigger its event. The following example shows how to trigger an input element’s change event and a button’s click event:
// Find input element by placeholder text
const input = screen.getByPlaceholderText('Name');
// Set input element's value
fireEvent.change(input, {target: {value: 'John'}});
// Find button element by text
const btn = screen.getByText('Submit');
// Click button
fireEvent.click(btn);
After the events are triggered, we can assert the expected behavior.
There is also a companion library for the Testing Library that is called user-event
. The...