Interactivity API - userEvent Guide

If you have been following the lessons so far, you may have noticed that interaction has been done directly on the Locator objects (which are returned from functions getByText()).

For example:

const button =
  await screen.getByRole('button');
await button.click();

There is also the Vitest Interactivity API, which matches a subset of the @testing-library/user-event functionality (you will recognise it from React Testing Library).

This interactivity API doesn't fake events (like the @testing-library/user-event package), but instead uses the Chrome DevTools Protocol (or webdriver), so it is much more realistic.

You import the interactivity API by importing userEvent from vitest/browser:

import { userEvent } from 'vitest/browser';

await userEvent.click(
  document.querySelector('.button')
);

When to use the userEvent from the Vitest Browser Mode Interactivity API

Generally you will not need to use this API, because you can call things like .click() directly on the Locator objects.

However, if you are doing something like const el = document.querySelector('.some-class') in your tests, then this will just return an HTMLElement.

In those cases you should call userEvent.click(el).

If you already know React Testing Library's UserEvent package, you will probably be able to breeze through this lesson as it is very similar.

In the rest of the lesson we will cover the main functions that you will want to use from this API.

Loading full lesson...