Setup: Creating a user-event Instance
What you'll learn: How to properly initialize user-event for reliable interaction tracking across your test suite.
The Core Idea
Up until now, you've seen that user-event is asynchronous and simulates real browser behavior. But there's a setup step you should use: creating a configured instance with userEvent.setup() before each test.
This function returns a user-event instance that internally tracks pointer position, keyboard state (which keys are pressed), and other interaction context. Without this setup, you'd be using default behavior that doesn't maintain state across multiple interactions in the same test.
Why Setup Matters
Think of userEvent.setup() as creating a "virtual user" for your test. This virtual user remembers:
- Where the pointer currently is on screen
- Which keys are currently held down
- The focus state
This matters when you chain interactions: clicking one element, then typing, then clicking another. The setup instance ensures these actions behave like a real user session, not isolated events.
The Pattern
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
it('tracks interactions correctly', async () => {
const user = userEvent.setup();
render(<MyForm />);
await user.click(screen.getByRole('button'));
await user.type(screen.getByRole('textbox'), 'Hello');
});
Call userEvent.setup() at the start of each test. Store the returned instance in a variable (commonly named user), then use that instance for all interactions.
This is now the recommended approach over importing methods directly from userEvent.
Key Takeaway: Always create a user-event instance with userEvent.setup() at the beginning of each test to ensure accurate pointer and keyboard state tracking across chained interactions.