Setup
When users interact in the browser by e.g. pressing keyboard keys, they interact
with a UI layer the browser shows to them. The browser then interprets this
input, possibly alters the underlying DOM accordingly and dispatches
trusted
events.
The UI layer and trusted events are not programmatically available.
Therefore user-event
has to apply workarounds and mock the UI layer to
simulate user interactions like they would happen in the browser.
Starting a session per setup()
setup(options?: Options): UserEvent
The userEvent.setup()
API applies these workarounds to the document and allows
you to configure an "instance" of user-event
.
Methods on this instance share one input device state, e.g. which keys are
pressed.
This allows to write multiple consecutive interactions that behave just like the described interactions by a real user.
import userEvent from '@testing-library/user-event'
const user = userEvent.setup()
await user.keyboard('[ShiftLeft>]') // Press Shift (without releasing it)
await user.click(element) // Perform a click with `shiftKey: true`
The instance exposes another .setup()
API that allows to configure another
instance that shares the same input device state.
The Clipboard API
is usually not available outside of secure context.
To enable testing of workflows involving the clipboard,
userEvent.setup()
replaces window.navigator.clipboard
with a
stub.
Direct APIs
You can also call the APIs directly on the default export. This will call
setup
internally and then use the method on the instance.
This exists to ease the transition to version 14 and writing simple tests. Using
the methods on the instances returned by userEvent.setup()
is recommended.