top of page

React Testing - IV [User Interactions]

When you display something on the browser, the user interacts with it. Say the button is clicked, typing in the input field, etc. That may come from the keyboard or mouse.

So, Testing is not about whether the component renders on the page or not but validating user interactions also.

CRA comes with a library called user-event.

Some may use 'fireEvent' method from RTL that dispatches Dom events, but user-event facilitates additional events, and we can do additional checks.

I chatted with ChatGPT, and gives me this response!

Both fireEvent and user-event simulate user interactions with a web page in tests.

However, there are some differences between the two:

fireEvent: This is part of the @testing-library/react library and is included in React's testing utilities.
It's a lower-level API that can be used to simulate DOM events such as click, change, submit, etc.
You'll need to provide the event type and any relevant event data as arguments to fireEvent.
user-event: This is a higher-level API that's designed to more closely mimic how a real user interacts with a web page.
It simulates a sequence of events, such as typing into a text field or clicking a button, and can handle things like focus and keyboard events automatically.
You typically don't need to provide as much detail as you would with fireEvent.
Pointer interactions:

I am using user-event version 13. x.x, but you can use the latest 14. x.

Pointer events are mostly concerned with mouse events like click, double-click, hover, etc.

We will have a counter-example here.

import userEvent from user-event and apply methods on it.

Use for simulating click in a test environment.

Keyboard interactions:

Most of the time, users interact with keyboards, mainly in form filling.

We will look at testing keyboard interactions.

We will validate an input field with type='number', simulate keyboard typing, and assert it.

Same with the button set.

Note: I have used userEvent.type and

bottom of page