React 33: Testing User Interactions
easy⏱ 5 mincoursereact
fireEvent vs userEvent
fireEvent dispatches DOM events directly—fast but not realistic. userEvent simulates real browser behavior: typing triggers focus, keydown, input, keyup events. Prefer userEvent for realistic tests.
// fireEvent - basic, direct
fireEvent.change(input, { target: { value: 'hello' } });
// userEvent - realistic, complete
await userEvent.type(input, 'hello');
// Simulates: focus, keydown, keypress, input, keyup for each character
Async testing
For async operations, use findBy queries (return promises) or wrap assertions in waitFor. Example: await screen.findByText('Loaded!') waits for the element to appear.
Test a search form
Create a SearchForm that filters a list as you type. Include simulated tests that: type in the search box, wait for filtered results, verify the correct items display.