Firing Events
Note
Most projects have a few use cases for
fireEvent, but the majority of the time you should probably use@testing-library/user-event.
fireEvent
Fire DOM events.
fireEvent[eventName]
Convenience methods for firing DOM events. Check out
src/event-map.js
for a full list as well as default eventProperties.
target: When an event is dispatched on an element, the event has the
subjected element on a property called target. As a convenience, if you
provide a target property in the eventProperties (second argument), then
those properties will be assigned to the node which is receiving the event.
This is particularly useful for a change event:
dataTransfer: Drag events have a dataTransfer property that contains data
transferred during the operation. As a convenience, if you provide a
dataTransfer property in the eventProperties (second argument), then those
properties will be added to the event.
This should predominantly be used for testing drag and drop interactions.
Keyboard events: There are three event types related to keyboard input -
keyPress, keyDown, and keyUp. When firing these you need to reference an
element in the DOM and the key you want to fire.
You can find out which key code to use at https://keycode.info/.
createEvent[eventName]
Convenience methods for creating DOM events that can then be fired by
fireEvent, allowing you to have a reference to the event created: this might
be useful if you need to access event properties that cannot be initiated
programmatically (such as timeStamp).
You can also create generic events:
Using Jest Function Mocks
Jest's Mock functions can be used to test that a callback passed to the function was called, or what it was called when the event that should trigger the callback function does trigger the bound callback.
- React