1. 19
    Simulate All User Interactions With an Element by Using the user-event Library
    1m 11s

Simulate All User Interactions With an Element by Using the user-event Library

Daniel Afonso
InstructorDaniel Afonso
Share this video with your friends

Social Share Links

Send Tweet

Whilst fireEvent helps to interact with elements, that is not how a user interacts with them. When a user interacts with an element, more than a single event is fired. This means that by using fireEvent, we might be missing some scenarios that might be triggered accidentally by other events.

In this lesson, we are going to learn about the companion library of the React Testing Library that allows you to simulate full interactions with your elements: the user-event library.

Instructor: [0:07] FireEvent is pretty useful, but there is something to be aware of when using it. That is, it only fires a single event. If we look at our UI and track all the events associated with clicking this button, you can see that there are more than just the click event associated with the act of firing an event.

[0:17] To make sure our FireEvents experience is as close to the one that the user has, the user-event library was created. Let us refactor the previous test case to leverage the user-event library and make sure we have a test case closer to the actual user experience.

[0:32] First, we need to import user-event from testing library user-event. Then, before we render, we need to call the user-event setup function. This function applies some workarounds to the UI layer to make sure that our user interactions happen the same way as they do in the browser.

[0:50] Once we call the setup function, it will give us a user instance. Using the user instance, let's replace our FireEvent click with user-click. Considering the click event is asynchronous, now we need to change our test to be asynchronous and wait for it.

[1:05] Now, if we run our test, we should see that it has passed and now we have a closer experience to our user.