Introduction
When we interact with any page or element in a browser, it triggers an event to execute the expected action or functionality. These events are called “User Events”. The User event is a companion library for the testing library that executes user events by triggering them based on the content and the interaction between user and browser. It makes triggering events easier for users and finds bugs. Let’s learn how to test user interactions and events in this article.
Testing User Events
Whenever you write any test, it should resemble the user interaction with your code. The fireEvent creates the user events and dispatches the event to the DOM node. Let’s look at the list of user events fired on user interactions.
- fireEvent.mouseOver(element) - fires the event handler when the user hovers over the element with the mouse.
- fireEvent.mouseMove(element) - fires the event handler when the user moves the element on the element or away from it.
- fireEvent.mouseDown(element) - fires the event handler when the when pointing button of the device is pressed while the pointer is inside the element.
- element.focus() - fires the event handler when the element is focused.
- fireEvent.mouseUp(element) - fires the event handler when the when pointing button of the device is released while the pointer is inside the element.
- fireEvent.click(element) - fires the event handler when the element is clicked.
- fireEvent.focus(element) - fires the event handler when the element is focused.
The above methods create events on mouse action and click events when a user interacts with any element on the webpage. Let’s learn how to test a few user events now.
keyDown
The keyDown event is dispatched when the user interacts with elements using the keyboard. This event is dispatched when the user focuses on any element. You can test the events in two ways.
fireEvent.keyDown(getByText('focus here'));
By directly using the fireEvent.keyDown() method with the query getByText to focus on the element with specific text.
getByText('focus here').focus();
fireEvent.keyDown(document.activeElement || document.body);
By fetching the element using the getByText query and focusing on it using the keyDown() method with the active element. This can also test the functionality of keyboard events on the webpage.
Focus/Blur
When the user focuses an element on the webpage, the element that is focused comes into view, and the previously focused element becomes blurred. The test will work only on the focusable elements. If the element doesn’t support the focus property, the test will fail along with the user event. This event can be tested in two ways.
fireEvent.focus(getByText('focus here'));
By directly using the fireEvent.focus() method with the getByText query by finding the matching element to test the focus functionality of the element.
getByText('focus here').focus();
By fetching the element using the getByText query method and then using the focus() method.