Skip to content

Latest commit

 

History

History
70 lines (55 loc) · 2.22 KB

intro.mdx

File metadata and controls

70 lines (55 loc) · 2.22 KB
id title
intro
Introduction

user-event is a companion library for Testing Library that simulates user interactions by dispatching the events that would happen if the interaction took place in a browser.

:::note Latest version

These docs describe user-event@14.
We recommend updating your projects to this version, as it includes important bug fixes and new features. You can find the docs for [email protected] here.

:::

While most examples with user-event are for React, the library can be used with any framework as long as there is a DOM.

Difference to fireEvent

The built-in fireEvent is a utility to easier dispatch events.
It dispatches exactly the events you tell it to and just those - even if those exact events never had been dispatched in a real interaction in a browser.

user-event on the other hand dispatches the events like they would happen if a user interacted with the document.
That might lead to the same events you previously dispatched per fireEvent directly, but it also might catch bugs that make it impossible for a user to trigger said events.
This is why you should use user-event to test interaction with your components.

Writing tests with userEvent

We recommend to use userEvent.setup() when rendering your component and inline that rendering and setup in your test or use a setup function.
We discourage rendering or using any userEvent functions outside of the test itself - e.g. in a before/after hook - for reasons described in "Avoid Nesting When You're Testing".

test('trigger some awesome feature when clicking the button', async () => {
    const user = userEvent.setup()
    render(<MyComponent/>)

    await user.click(screen.getByRole('button', name: /click me!/))

    // ...assertions...
})
function setup(jsx) {
  return {
    user: userEvent.setup(),
    ...render(jsx),
  }
}

test('render with a setup function', async () => {
  const {user} = setup(<MyComponent />)
  // ...
})