test("typing updates the greeting", async () => {
const user = userEvent.setup();
render(<Greeting />);
await user.type(screen.getByLabelText(/name/i), "Ana");
expect(screen.getByText("Hello, Ana")).toBeInTheDocument();
});
fireEvent dispatches one single DOM event. userEvent simulates the full interaction a real user performs. Prefer userEvent.
fireEvent: fireEvent.change(input, { target: { value: 'hi' } }) sets the value in one go. It fires no focus, keydown, keypress, input or keyup events.
userEvent (v14):
await user.type(input, 'hi')clicks the element and focuses it. Then it fires the keyboard and input events for each character.user.clickfires pointer and mouse events and moves focus.- It also respects things like disabled elements.
How to use userEvent: create an instance with const user = userEvent.setup(). Then await every call, because the API is async.
Why prefer it: it catches bugs that fireEvent hides. Examples are a handler on onKeyDown, or focus logic. Use fireEvent only for events userEvent doesn't cover, such as scroll.
fireEventdispatches one single event.userEventsimulates the full sequence of focus, key and input events.- In v14, create an instance with
userEvent.setup()and await every call. userEventcatches bugs in keyboard and focus handling.- Use
fireEventonly for gaps likescroll.
Read more
- user-event intro (https://testing-library.com/docs/user-event/intro)testing-library.com