### Setup Function Usage Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Example of using the setup function to create a userEvent instance and perform interactions.
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
// State is preserved across calls
await user.click(input)
await user.keyboard('hello')
```
--------------------------------
### Setup Instance Behavior Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Example illustrating preserved state across multiple method calls when using a setup instance of userEvent.
```typescript
const user = userEvent.setup()
// State is preserved
await user.click(input)
await user.keyboard('{Control>}a{/Control}') // Shift is still pressed from above
```
--------------------------------
### EventTypeInit Examples
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/types.md
Examples demonstrating the usage of EventTypeInit.
```typescript
EventTypeInit<'click'> // => MouseEventInit
EventTypeInit<'input'> // => InputEventInit
EventTypeInit<'paste'> // => ClipboardEventInit
```
--------------------------------
### document Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Example demonstrating the document option for testing in iframes or isolated contexts.
```typescript
// In a test with JSDOM
const container = document.createElement('div')
document.body.appendChild(container)
const {rerender} = render(, {container})
const user = userEvent.setup({document: container.ownerDocument})
await user.type(screen.getByRole('textbox'), 'test')
```
--------------------------------
### applyAccept Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Example demonstrating the applyAccept option for file uploads.
```typescript
const input = screen.getByLabelText(/upload/i) // accept="image/*"
const user = userEvent.setup()
const imageFile = new File(['...'], 'test.png', {type: 'image/png'})
const textFile = new File(['...'], 'test.txt', {type: 'text/plain'})
// applyAccept: true (default)
await user.upload(input, imageFile) // ✓ Added
await user.upload(input, textFile) // ✗ Rejected
// applyAccept: false
await user.upload(input, [imageFile, textFile], {applyAccept: false})
// Both files added
```
--------------------------------
### Custom Keyboard Layouts
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Example of passing a custom keyboard map to setup() or an API call to use a Dvorak layout.
```typescript
// Dvorak layout (simplified example)
const dvorakLayout = [
{code: 'KeyA', key: 'a'},
{code: 'KeyO', key: 'o'}, // Different from QWERTY
{code: 'KeyE', key: 'e'}, // Different from QWERTY
// ... more mappings
]
const user = userEvent.setup({keyboardMap: dvorakLayout})
await user.click(input)
await user.keyboard('hello') // Uses Dvorak mapping
```
--------------------------------
### delay Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Example demonstrating the delay option for keyboard input.
```typescript
const user = userEvent.setup({delay: 100})
// Each character has 100ms delay between keydown/keyup
await user.keyboard('hello')
// No delay
const userFast = userEvent.setup({delay: null})
await userFast.keyboard('hello')
```
--------------------------------
### Project Setup Commands
Source: https://github.com/testing-library/user-event/blob/main/CONTRIBUTING.md
Commands to set up the project after forking and cloning the repository.
```bash
npm run setup -s
```
```bash
git checkout -b pr/your-branch-name
```
--------------------------------
### autoModify Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Example demonstrating the autoModify option for keyboard input.
```typescript
const user = userEvent.setup({autoModify: false})
// Future: Would require manual Shift{>} for uppercase
await user.keyboard('{Shift>}HELLO{/Shift}')
```
--------------------------------
### AZERTY layout example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Example of defining a custom keyboard map for an AZERTY layout and using it with the `user.keyboard()` method.
```typescript
const azertyLayout = [
{code: 'KeyA', key: 'q'},
{code: 'KeyQ', key: 'a'},
{code: 'KeyW', key: 'z'},
// ... more keys
]
const user = userEvent.setup({keyboardMap: azertyLayout})
await user.keyboard('hello') // Uses AZERTY mapping
```
--------------------------------
### Keyboard Input Examples
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/types.md
Examples of using the `keyboard()` function with special notation.
```typescript
// Simple text
await user.keyboard('hello world')
// With modifiers
await user.keyboard('{Shift>}HELLO{/Shift}')
// With special keys
await user.keyboard('{Control>}a{/Control}') // Select all
await user.keyboard('{Meta>}z{/Meta}') // Undo
// Multiple keys
await user.keyboard('{Control>}{Shift>}z{/Shift}{/Control}') // Redo
// Combinations
await user.keyboard('Type: {Shift>}hello{/Shift} {Enter}World')
```
--------------------------------
### PointerInput Examples
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/types.md
Examples of PointerInput usage.
```typescript
// Move to element
{target: element}
// Click at specific coordinates
{coords: {clientX: 100, clientY: 200}, keys: '[MouseLeft]'}
// Sequence of actions
[
{target: button},
'[MouseLeft>]',
{target: otherElement},
'[/MouseLeft]'
]
```
--------------------------------
### Setup Configuration
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
When using userEvent.setup(), the configuration is applied to all subsequent API calls on that instance.
```typescript
const user = userEvent.setup({
delay: 10,
skipHover: true,
writeToClipboard: true,
})
// All calls will use the setup configuration
await user.click(button)
await user.keyboard('text')
```
```typescript
const user = userEvent.setup({delay: 10})
const userFast = user.setup({delay: 0})
// user has 10ms delay
// userFast has 0ms delay
```
--------------------------------
### Pointer events check levels example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Examples demonstrating different levels of `pointerEventsCheck` configuration for performance optimization and thoroughness.
```typescript
// Performance optimization for large DOMs
const user = userEvent.setup({
pointerEventsCheck: PointerEventsCheckLevel.Never
})
// Normal operation
const user2 = userEvent.setup({
pointerEventsCheck: PointerEventsCheckLevel.EachApiCall
})
// Very thorough checking
const user3 = userEvent.setup({
pointerEventsCheck: PointerEventsCheckLevel.EachTrigger
})
```
--------------------------------
### Pointer Input Examples
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/types.md
Examples of using the `pointer()` function with special notation.
```typescript
// Click
await user.pointer([{target: button}, '[MouseLeft]'])
// Drag
await user.pointer([
{target: element},
'[MouseLeft>]',
{coords: {x: 100, y: 200}},
'[/MouseLeft]'
])
// Multi-touch
await user.pointer([
{target: element, pointerName: 'touch1'},
'[TouchA>]',
{pointerName: 'touch2', coords: {x: 50, y: 100}},
'[TouchB>]',
'[/TouchA]',
'[/TouchB]'
])
```
--------------------------------
### Keyboard Notation Examples
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Examples illustrating different keyboard key notations for pressing, holding, and releasing keys.
```plaintext
{Enter} Enter key
{Shift>}a{/Shift} Shift+A
{Control>}z{/Control} Ctrl+Z
```
--------------------------------
### Setup and Teardown
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Create a session with shared state and sub-instances with different options.
```typescript
import userEvent from '@testing-library/user-event'
// Create a session with shared state
const user = userEvent.setup()
// Sub-instance with different options, same state
const userFast = user.setup({delay: 0})
```
--------------------------------
### delay Advanced Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Advanced example showing how delay can be used for testing debounced search.
```typescript
// For testing debounced search
const user = userEvent.setup({delay: 200})
const searchInput = screen.getByPlaceholderText('Search')
await user.type(searchInput, 'react', {delay: null})
// Debounce timer not triggered yet
await user.type(searchInput, ' hooks', {delay: 200})
// Now debounce triggers and search executes
```
--------------------------------
### Advanced advanceTimers Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Provides an example of using a custom timer implementation with the `advanceTimers` option.
```typescript
// Custom timer implementation
const user = userEvent.setup({
advanceTimers: async (ms) => {
// Custom timer system
await myTimerSystem.advance(ms)
},
delay: 50
})
await user.keyboard('test')
```
--------------------------------
### Pointer Notation Examples
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Examples of pointer notation for mouse clicks, touch points, and movement.
```plaintext
[MouseLeft] Click
[MouseRight] Right-click
[MouseMiddle] Middle-click
[TouchA] Touch point
{target: el} Move to element
{coords: {...}} Move to coordinates
```
--------------------------------
### Custom pointer map example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Example of defining a custom pointer map including mouse, pen, and touch devices, and using it with the `user.pointer()` method.
```typescript
const customPointerMap = [
{name: 'MouseLeft', pointerType: 'mouse', button: 'primary'},
{name: 'MouseRight', pointerType: 'mouse', button: 'secondary'},
{name: 'MouseMiddle', pointerType: 'mouse', button: 'auxiliary'},
{name: 'PenPrimary', pointerType: 'pen', button: 'primary'},
{name: 'PenEraser', pointerType: 'pen', button: 'eraser'},
{name: 'TouchA', pointerType: 'touch'},
{name: 'TouchB', pointerType: 'touch'},
]
const user = userEvent.setup({pointerMap: customPointerMap})
await user.pointer('[PenPrimary]')
```
--------------------------------
### With clipboard
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of setting up userEvent with writeToClipboard enabled.
```typescript
// With clipboard
const user = userEvent.setup({writeToClipboard: true})
```
--------------------------------
### userEvent.tab Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Examples of simulating forward and backward tab navigation.
```typescript
const user = userEvent.setup()
// Forward tab
await user.tab()
// Backward tab (Shift+Tab)
await user.tab({ shift: true })
```
--------------------------------
### Always Use Setup for Tests
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Demonstrates the recommended way to use userEvent.setup() in tests.
```typescript
// ✅ Good
const user = userEvent.setup()
await user.type(input, 'text')
await user.click(button)
// ⚠️ Avoid (separate state)
await userEvent.type(input, 'text')
await userEvent.click(button)
```
--------------------------------
### Setup Instance Defaults
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Lists the default configuration options applied when using `userEvent.setup()`, including overrides from direct API defaults.
```json
{
// ... all direct defaults, plus:
writeToClipboard: true,
}
```
--------------------------------
### advanceTimers Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Demonstrates how to configure `advanceTimers` with `jest.useFakeTimers()` to manage delay processing.
```typescript
jest.useFakeTimers()
const user = userEvent.setup({
advanceTimers: jest.advanceTimersByTime,
delay: 100
})
const input = screen.getByRole('textbox')
// Each character waits 100ms with jest fake timers
await user.type(input, 'hello')
jest.runOnlyPendingTimers()
```
--------------------------------
### userEvent.pointer Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Examples of simulating pointer interactions like clicks, touches, and multi-action sequences.
```typescript
const user = userEvent.setup()
// Click by moving and pressing mouse button
await user.pointer([{target: button}, '[MouseLeft]'])
// Touch interaction
await user.pointer({pointerType: 'touch', target: element})
// Multiple actions
await user.pointer([
{target: element},
'[MouseLeft>]',
{coords: {x: 100, y: 100}},
'[/MouseLeft]',
])
```
--------------------------------
### userEvent.hover Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Example of hovering over a link element.
```typescript
const user = userEvent.setup()
const link = screen.getByRole('link')
await user.hover(link)
```
--------------------------------
### writeToClipboard Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Shows how to use the `writeToClipboard` option to control whether data is written to the Clipboard API.
```typescript
// Direct API: doesn't write to clipboard
const data = await userEvent.copy()
navigator.clipboard.readText() // Rejects
// Setup with clipboard enabled
const user = userEvent.setup({writeToClipboard: true})
await user.copy()
const text = await navigator.clipboard.readText() // Works
// Paste data back
await user.paste(text)
```
--------------------------------
### userEvent.keyboard Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Examples of simulating keyboard input, including special keys and modifier keys.
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
await user.click(input)
// Simple typing
await user.keyboard('hello')
// With special keys
await user.keyboard('{Enter}')
await user.keyboard('{Shift>}Hello{/Shift}')
await user.keyboard('{Control>}a{/Control}')
```
--------------------------------
### Skip auto-close example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Examples illustrating the use of `skipAutoClose` to control whether pressed keys are automatically released after `type()`.
```typescript
const user = userEvent.setup()
// Normal: keys are released
await user.type(input, 'hello')
// No keys pressed after this call
// Custom: keep Shift pressed
await user.type(input, 'hello', {skipAutoClose: true})
await user.keyboard('world') // Shift still held
await user.keyboard('{/Shift}')
// Modifier combinations
await user.keyboard('{Control>}')
await user.type(input, 'a', {skipAutoClose: true})
// Control is still pressed
```
--------------------------------
### dblClick Method Usage Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Example of simulating a double-click on a textbox using the userEvent instance.
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
await user.dblClick(input)
```
--------------------------------
### Setup Session vs Direct API
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Demonstrates the difference between setting up a session for preserved state and using the direct API for isolated calls.
```typescript
const user = userEvent.setup()
await user.click(element)
await user.type(input, 'text')
// State preserved across calls
```
```typescript
await userEvent.click(element)
await userEvent.type(input, 'text')
// Each call is independent
```
--------------------------------
### User uploaded a file
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of simulating user file upload.
```typescript
await user.upload(fileInput, file)
```
--------------------------------
### Configuration Merging Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Demonstrates how parent configuration is merged with new options for sub-instances and API calls, ensuring all fields are present.
```typescript
const user = userEvent.setup({delay: 100, skipHover: true})
// Sub-instance overrides delay
const userFast = user.setup({delay: 0})
// Result: delay=0, skipHover=true (inherited)
// API call adds option
await user.click(button, {skipClick: true})
// Result: delay=100, skipHover=true, skipClick=true
```
--------------------------------
### Click Method Usage Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Example of simulating a click on a button using the userEvent instance.
```typescript
const user = userEvent.setup()
const button = screen.getByRole('button', { name: /submit/i })
await user.click(button)
```
--------------------------------
### Direct API Behavior Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Example demonstrating the isolated system state when calling methods directly on the userEvent object.
```typescript
import userEvent from '@testing-library/user-event'
// Each call is isolated
await userEvent.click(button)
// Keyboard state is not preserved
await userEvent.keyboard('text')
```
--------------------------------
### skipClick Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Demonstrates the usage of the `skipClick` option in `userEvent.type()` to control whether an initial click event is dispatched.
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
// Normal: clicks first
await user.type(input, 'hello')
// Dispatches: click, pointerdown, pointerup, ...
// Skip click
await user.click(input)
await user.type(input, 'hello', {skipClick: true})
// Only keyboard events
```
--------------------------------
### Custom keyboard layout
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of setting up userEvent with a custom keyboard layout.
```typescript
// Custom keyboard layout
const user = userEvent.setup({keyboardMap: dvorakLayout})
```
--------------------------------
### Coordinate Systems - Viewport coordinates
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Example of using clientX and clientY for viewport-relative coordinates.
```typescript
const user = userEvent.setup()
// Viewport coordinates
await user.pointer({
target: element,
coords: {clientX: 50, clientY: 100}
})
```
--------------------------------
### Enable Verbose Logging
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/errors.md
Example of setting up a try-catch block with detailed logging for errors during user actions.
```typescript
// Set up try-catch with logging
try {
await user.someAction(element)
} catch (error) {
console.error('Action failed:', {
message: error.message,
stack: error.stack,
element: element.tagName,
elementId: element.id,
elementClass: element.className,
})
}
```
--------------------------------
### Fast execution
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of setting up userEvent with a delay of 0 for fast execution.
```typescript
// Fast execution
const user = userEvent.setup({delay: 0})
```
--------------------------------
### Trigger tooltip
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Example of hovering over a link to trigger a tooltip and then asserting its presence.
```typescript
const user = userEvent.setup()
// Trigger tooltip
const link = screen.getByRole('link')
await user.hover(link)
const tooltip = await screen.findByRole('tooltip')
expect(tooltip).toBeInTheDocument()
```
--------------------------------
### User selected from dropdown
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of simulating user selection from a dropdown.
```typescript
await user.selectOptions(select, 'value')
```
--------------------------------
### Creating Custom Layout
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Example of creating a custom keyboard layout using `keyboardKey` type.
```typescript
import {DOM_KEY_LOCATION, keyboardKey} from '@testing-library/user-event'
const customLayout: keyboardKey[] = [
// Regular keys
{code: 'KeyA', key: 'a'},
{code: 'KeyA', key: 'A', shift: true},
// With location
{
code: 'ShiftLeft',
key: 'Shift',
location: DOM_KEY_LOCATION.LEFT
},
// With AltGr
{code: 'KeyE', key: 'é', altGr: true},
// Function keys
{code: 'Enter', key: 'Enter'},
{code: 'Escape', key: 'Escape'},
]
```
--------------------------------
### Navigate backward
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Example of simulating Shift+Tab to move focus backward to the previous input field.
```typescript
const user = userEvent.setup()
// Navigate backward
await user.tab({shift: true})
expect(input1).toHaveFocus()
```
--------------------------------
### Testing Keyboard Navigation
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Example of testing keyboard navigation using tab() to move focus between menu items.
```typescript
const user = userEvent.setup()
const items = screen.getAllByRole('menuitem')
expect(items[0]).toHaveFocus()
await user.tab()
expect(items[1]).toHaveFocus()
await user.tab({shift: true})
expect(items[0]).toHaveFocus()
```
--------------------------------
### Navigate forward
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Example of simulating a Tab press to move focus from one input field to the next.
```typescript
const user = userEvent.setup()
// Navigate forward
const input1 = screen.getByRole('textbox')
const input2 = screen.getAllByRole('textbox')[1]
await user.click(input1)
await user.tab()
expect(input2).toHaveFocus()
```
--------------------------------
### keyboard() - Low Level
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Example of using the keyboard() method for low-level key event simulation.
```typescript
const user = userEvent.setup()
await user.click(input)
await user.keyboard('hello')
```
--------------------------------
### skipHover Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Illustrates the `skipHover` option in `userEvent.click()` to prevent the implicit hover/move event before clicking.
```typescript
const user = userEvent.setup()
const button = screen.getByRole('button')
// Normal: hovers then clicks
await user.click(button)
// Dispatches: pointerover, pointerenter, pointerdown, pointerup, click
// Skip hover
await user.click(button, {skipHover: true})
// Dispatches: pointerdown, pointerup, click (no pointerover)
```
--------------------------------
### Coordinate Systems - Screen coordinates
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Example of using screenX and screenY for screen-relative coordinates.
```typescript
// Screen coordinates (rare)
await user.pointer({
target: element,
coords: {screenX: 800, screenY: 600}
})
```
--------------------------------
### User typed in an input
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of simulating user text input.
```typescript
await user.type(input, 'text')
```
--------------------------------
### User clicked a button
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of simulating a user click on a button.
```typescript
await user.click(button)
```
--------------------------------
### Testing Button States
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Example of testing button interactions including hover, click, and unhover states.
```typescript
const user = userEvent.setup()
const button = screen.getByRole('button')
// Hover
await user.hover(button)
expect(button).toHaveClass('hover')
// Click
await user.click(button)
expect(screen.getByText('Clicked')).toBeInTheDocument()
// Unhover
await user.unhover(button)
expect(button).not.toHaveClass('hover')
```
--------------------------------
### User pressed keyboard shortcut
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of simulating a user pressing a keyboard shortcut.
```typescript
await user.keyboard('{Control>}s{/Control}') // Ctrl+S
```
--------------------------------
### Handle Delays for Async Code
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Shows how to handle delays for asynchronous code, either by setting a delay in setup or using findBy.
```typescript
// ✅ Good (with delay)
const user = userEvent.setup({delay: 100})
await user.type(input, 'search')
// Debounce handler has time to work
// Or use findBy with proper wait
const results = await screen.findByRole('listbox')
```
--------------------------------
### Testing IME Input
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Example of manually dispatching composition events to test IME input.
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
await user.click(input)
// Simulate IME composition
const compositionStart = new CompositionEvent('compositionstart', {
data: 'テ'
})
input.dispatchEvent(compositionStart)
const compositionUpdate = new CompositionEvent('compositionupdate', {
data: 'テスト'
})
input.dispatchEvent(compositionUpdate)
const compositionEnd = new CompositionEvent('compositionend', {
data: '日本語'
})
input.dispatchEvent(compositionEnd)
```
--------------------------------
### Check hover styles
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Example of hovering over a button and asserting that it gains a 'hover' class.
```typescript
const user = userEvent.setup()
// Check hover styles
const button = screen.getByRole('button')
await user.hover(button)
expect(button).toHaveClass('hover')
```
--------------------------------
### Pointer Events Check Configuration
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Examples of configuring the `pointerEventsCheck` option for different levels of thoroughness.
```typescript
// Skip check (fast, but might miss disabled elements)
const user = userEvent.setup({
pointerEventsCheck: PointerEventsCheckLevel.Never
})
// Check once per API call (default)
const user = userEvent.setup({
pointerEventsCheck: PointerEventsCheckLevel.EachApiCall
})
// Check each target (more thorough)
const user = userEvent.setup({
pointerEventsCheck: PointerEventsCheckLevel.EachTarget
})
// Check every trigger (most thorough, slowest)
const user = userEvent.setup({
pointerEventsCheck: PointerEventsCheckLevel.EachTrigger
})
```
--------------------------------
### userEvent.unhover Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Example of moving the pointer away from a button element.
```typescript
const user = userEvent.setup()
const button = screen.getByRole('button')
await user.unhover(button)
```
--------------------------------
### Pointer Input Types - Array of actions
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Example of using an array of actions for sequential pointer input.
```typescript
[{target: element}, '[MouseLeft]', {coords: {x: 200, y: 200}}]
```
--------------------------------
### Coordinate Systems - Element-relative coordinates
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Example of using offsetX and offsetY for element-relative coordinates.
```typescript
// Element-relative coordinates
await user.pointer({
target: element,
coords: {offsetX: 10, offsetY: 20}
})
```
--------------------------------
### Key State Tracking Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Shows how the keyboard system tracks pressed keys, including pressing and holding a modifier key.
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
await user.click(input)
// Press Shift without releasing
await user.keyboard('{Shift>}')
// Type 'a' - Shift is still held
await user.keyboard('a')
// Release Shift
await user.keyboard('{/Shift}')
```
--------------------------------
### Test Keyboard Shortcut
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Example of testing a keyboard shortcut (Ctrl+S) using the keyboard API.
```typescript
const user = userEvent.setup()
await user.click(button)
// Simulate Ctrl+S (Save)
await user.keyboard('{Control>}s{/Control}')
expect(saveFunction).toHaveBeenCalled()
```
--------------------------------
### Testing Form Input with Cleanup
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Example of testing form input interactions, including focus changes and typing.
```typescript
const user = userEvent.setup()
await user.click(input1)
await user.type(input1, 'value1')
await user.click(input2)
expect(input1).not.toHaveFocus()
await user.type(input2, 'value2')
```
--------------------------------
### Pointer Input Types - Single action object
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Examples of using single action objects for pointer input, including target, coordinates, and keys.
```typescript
{target: element}
{coords: {x: 100, y: 100}}
{target: element, keys: '[MouseLeft]'}
```
--------------------------------
### tripleClick Method Usage Example
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Example of simulating a triple-click on a textbox using the userEvent instance.
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
await user.tripleClick(input)
```
--------------------------------
### Check tooltip removal
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Example of hovering over a link to show a tooltip, then unhovering to remove it and asserting its absence.
```typescript
const user = userEvent.setup()
const link = screen.getByRole('link')
await user.hover(link)
const tooltip = await screen.findByRole('tooltip')
await user.unhover(link)
expect(tooltip).not.toBeInTheDocument()
```
--------------------------------
### Parameter Table Format
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/MANIFEST.md
Demonstrates the consistent format used for parameter tables across all methods.
```markdown
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
```
--------------------------------
### Setting up upstream remote
Source: https://github.com/testing-library/user-event/blob/main/CONTRIBUTING.md
Commands to add the original repository as an upstream remote and configure local branches to pull from it.
```bash
git remote add upstream https://github.com/testing-library/user-event
git fetch upstream
git branch --set-upstream-to=upstream/main main
```
--------------------------------
### Simulate cutting selected content to clipboard.
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Usage Example for userEvent.cut
```typescript
const user = userEvent.setup({ writeToClipboard: true })
const input = screen.getByRole('textbox')
input.value = 'text to cut'
await user.click(input)
const clipData = await user.cut()
```
--------------------------------
### Simulate copying selected content to clipboard.
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Usage Example for userEvent.copy
```typescript
const user = userEvent.setup({ writeToClipboard: true })
const input = screen.getByRole('textbox')
await user.click(input)
await user.keyboard('{Control>}c{/Control}')
const clipData = await user.copy()
```
--------------------------------
### Running Tests and Updating Snapshots
Source: https://github.com/testing-library/user-event/blob/main/CONTRIBUTING.md
Commands to run tests and update any necessary snapshots before committing changes.
```bash
npm run test:update
```
--------------------------------
### Clear the value of an input or contenteditable element.
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Usage Example for userEvent.clear
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
input.value = 'existing text'
await user.clear(input)
```
--------------------------------
### Type text into an input or contenteditable element.
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Usage Example for userEvent.type
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
await user.type(input, 'hello world')
// With initial selection
await user.type(input, 'new text', {
initialSelectionStart: 0,
initialSelectionEnd: 5,
})
// With special keys
await user.type(input, 'Hello{Enter}World')
```
--------------------------------
### uploadInit Interface
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/types.md
Options for the upload() function. Currently unused but available for future extensions.
```typescript
export interface uploadInit {
changeInit?: EventInit
}
```
--------------------------------
### Event Sequence Documentation Format
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/MANIFEST.md
Illustrates the clear documentation of DOM events fired by user interactions.
```markdown
Event1 → Event2 → Event3
(with explanations)
```
--------------------------------
### Pointer State Tracking
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Get the system state after a pointer operation.
```typescript
const system = await userEvent.pointer({target: button})
// Get current position
const position = system.pointer.getPreviousPosition('mouse')
console.log(position)
// {
// target: button,
// coords: {...},
// caret: {...}
// }
// Get pointer names
const pointerNames = system.pointer.pointers
```
--------------------------------
### User copied text
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of simulating a user copying text.
```typescript
const data = await user.copy()
```
--------------------------------
### Direct API Defaults
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
Lists the default configuration options applied when calling user-event methods directly.
```json
{
applyAccept: true,
autoModify: true,
delay: 0,
document: globalThis.document,
keyboardMap: defaultKeyboardMap,
pointerMap: defaultPointerMap,
pointerEventsCheck: PointerEventsCheckLevel.EachApiCall,
skipAutoClose: false,
skipClick: false,
skipHover: false,
writeToClipboard: false,
advanceTimers: () => Promise.resolve(),
}
```
--------------------------------
### Direct API (isolated state)
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Demonstrates using the keyboard API directly without a setup instance, showing independent calls and returning the System object.
```typescript
// Each call is independent
await userEvent.keyboard('hello')
await userEvent.keyboard('{Enter}')
// Returns the System object
const system = await userEvent.keyboard('text')
console.log(system.keyboard.getPressedKeys())
```
--------------------------------
### User hovered over element
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of simulating a user hovering over an element.
```typescript
await user.hover(element)
```
--------------------------------
### selectOptions() vs click()
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/utility.md
Compares the high-level `selectOptions()` API with its low-level equivalent using `click()` on an option element.
```typescript
// High-level selectOptions()
await user.selectOptions(select, 'value')
// Low-level equivalent
await user.click(optionElement)
```
--------------------------------
### Element Could Not Be Focused Recovery
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/errors.md
Example of how to recover from the 'clear()' error when the element cannot be focused.
```typescript
// Ensure element is focusable
element.disabled = false
element.style.display = 'block'
try {
await user.clear(element)
} catch (e) {
if (e.message.includes('could not be focused')) {
// Manually clear if focus fails
element.value = ''
element.dispatchEvent(new Event('input', {bubbles: true}))
}
}
```
--------------------------------
### Element Not Editable Recovery
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/errors.md
Example of how to recover from the 'clear()' error when called on a non-editable element.
```typescript
try {
await user.clear(nonEditableElement)
} catch (e) {
if (e.message.includes('only supported on editable')) {
// Use a different approach for this element
element.innerText = '' // Direct DOM manipulation
}
}
```
--------------------------------
### Event Sequence: dblClick()
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
The sequence of events triggered by the dblClick() convenience method.
```plaintext
(pointerover → pointerenter → mouseover → mouseenter) ×2
(pointerdown → mousedown → pointerup → mouseup → click) ×2
dblclick
```
--------------------------------
### Test Context Menu
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Demonstrates how to simulate a right-click to open a context menu and then click an option within that menu.
```typescript
const user = userEvent.setup()
const element = screen.getByRole('button')
// Right-click
await user.pointer([
{target: element},
'[MouseRight]'
])
// Menu appears
const deleteOption = await screen.findByText('Delete')
expect(deleteOption).toBeInTheDocument()
// Click menu option
await user.click(deleteOption)
```
--------------------------------
### Delayed Input
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Example of using the `delay` option to add time between key presses.
```typescript
const user = userEvent.setup({delay: 100})
// Each key has 100ms delay
await user.keyboard('hello')
// Fast input
const userFast = userEvent.setup({delay: 0})
await userFast.keyboard('hello')
// Per-call delay
await user.keyboard('hello', {delay: 50})
```
--------------------------------
### tab() vs keyboard()
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Compares the convenience tab() method with the lower-level keyboard() API, showing how tab() handles special cases and keyboard() allows key combinations.
```typescript
const user = userEvent.setup()
// Convenience (explicit intent)
await user.tab()
await user.tab({shift: true})
// Low-level (explicit key codes)
await user.keyboard('{Tab}')
await user.keyboard('{Shift>}{Tab}{/Shift}')
```
--------------------------------
### Usage in Event Handlers
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Example of how to use the pointer API within event handlers.
```typescript
const user = userEvent.setup()
const input = screen.getByRole('textbox')
input.addEventListener('click', (e) => {
// Can read position from event
console.log('Clicked at offset:', e.offset)
})
await user.pointer({target: input, offset: 5})
```
--------------------------------
### User pasted from clipboard
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of simulating a user pasting text from the clipboard.
```typescript
await user.paste('text')
```
--------------------------------
### Error Conditions Table Format
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/MANIFEST.md
Shows the clear table format used for documenting error conditions.
```markdown
| Error | Condition | Recovery |
|-------|-----------|----------|
```
--------------------------------
### click() vs pointer()
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Compares the convenience click() method with the lower-level pointer() API, highlighting differences in hover behavior and control.
```typescript
const user = userEvent.setup()
// Convenience method (same outcome)
await user.click(button)
// Low-level API
await user.pointer([{target: button}, '[MouseLeft]'])
```
--------------------------------
### Copy then Keyboard
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/clipboard.md
Demonstrates a workflow where content is copied using keyboard shortcuts (simulated with `userEvent.keyboard`) and then pasted into another element.
```typescript
const user = userEvent.setup({writeToClipboard: true})
const input = screen.getByRole('textbox')
input.value = 'content'
await user.click(input)
// Copy
await user.keyboard('{Control>}c{/Control}')
await user.copy()
// Switch to another element
const input2 = screen.getAllByRole('textbox')[1]
await user.click(input2)
// Paste
await user.keyboard('{Control>}v{/Control}')
await user.paste()
```
--------------------------------
### DOM Testing Library Integration
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of integrating user-event with DOM Testing Library.
```typescript
import {getByRole} from '@testing-library/dom'
import userEvent from '@testing-library/user-event'
it('types in input', async () => {
const user = userEvent.setup()
const input = getByRole(document.body, 'textbox')
await user.type(input, 'hello')
})
```
--------------------------------
### Vue Test Utils Integration
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of integrating user-event with Vue Test Utils.
```typescript
import {mount} from '@vue/test-utils'
import userEvent from '@testing-library/user-event'
it('types in input', async () => {
const user = userEvent.setup()
const wrapper = mount(InputComponent)
await user.type(wrapper.find('input').element, 'hello')
})
```
--------------------------------
### Direct API Configuration
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/configuration.md
When calling methods directly on userEvent, options are passed per-call.
```typescript
await userEvent.click(button, {skipHover: true})
await userEvent.keyboard('text', {delay: 50})
```
--------------------------------
### React Testing Library Integration
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of integrating user-event with React Testing Library.
```typescript
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
it('types in input', async () => {
const user = userEvent.setup()
render()
const input = screen.getByRole('textbox')
await user.type(input, 'hello')
})
```
--------------------------------
### Event Sequence: click()
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
The sequence of events triggered by the click() convenience method.
```plaintext
pointerover → pointerenter → mouseover → mouseenter →
pointerdown → mousedown → pointerup → mouseup → click
```
--------------------------------
### Performance optimization
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Example of setting up userEvent for performance optimization by setting pointerEventsCheck to Never.
```typescript
// Performance optimization
const user = userEvent.setup({
pointerEventsCheck: PointerEventsCheckLevel.Never
})
```
--------------------------------
### Safe API Calls - Safe type()
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/errors.md
An example of a safe type function that includes pre-flight checks.
```typescript
const user = userEvent.setup()
// Safe type() with checks
async function safeType(element, text) {
try {
validateInput(element)
await user.type(element, text)
} catch (error) {
console.error('Type failed:', error.message)
throw error
}
}
```
--------------------------------
### Multiple Formats
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/clipboard.md
Demonstrates that setting many different data formats on a `DataTransfer` object is a fast operation within `user-event`.
```typescript
// Setting many formats is fast
const dt = new DataTransfer()
for (let i = 0; i < 100; i++) {
dt.setData(`format${i}`, `data${i}`)
}
```
--------------------------------
### type() - High Level
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/keyboard.md
Example of using the type() method for high-level text input simulation.
```typescript
const user = userEvent.setup()
await user.type(input, 'hello')
```
--------------------------------
### EventTypeInit Type
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/types.md
Maps an event type to its init properties. Automatically selects the appropriate `*EventInit` interface based on event type.
```typescript
export type EventTypeInit = SpecificEventInit<
FixedDocumentEventMap[K]
>
```
--------------------------------
### click
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/convenience.md
Simulate a click on an element.
```typescript
const user = userEvent.setup()
const button = screen.getByRole('button')
await user.click(button)
// Skip hover phase
await user.click(button, {skipHover: true})
// Direct API (creates isolated state)
await userEvent.click(button)
```
```typescript
// click() - High level
await user.click(button)
// pointer() - Low level equivalent
await user.pointer([{target: button}, '[MouseLeft]'])
```
--------------------------------
### Recovery for Invalid Pointer Name
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/errors.md
Example of how to recover from an error when trying to access a non-existent pointer name.
```typescript
const user = userEvent.setup()
// Valid touch pointers: TouchA, TouchB, TouchC
await user.pointer([{pointerName: 'TouchA'}, '[TouchA>]'])
// Invalid: TouchD doesn't exist
try {
await user.pointer('[TouchD]')
} catch (e) {
console.log('Use TouchA, TouchB, or TouchC')
}
```
--------------------------------
### type() vs keyboard()
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/utility.md
Compares the high-level `type()` API with its low-level equivalent using `click()` and `keyboard()`.
```typescript
// High-level type()
await user.type(input, 'hello')
// Low-level equivalent
await user.click(input)
await user.keyboard('hello')
await releaseAllKeys(instance)
```
--------------------------------
### Cannot Deselect Non-Multiple Select Recovery
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/errors.md
Example of how to recover from the 'Unable to deselect an option in a non-multiple select' error.
```typescript
const select = screen.getByRole('combobox')
try {
await user.deselectOptions(select, 'current-value')
} catch (e) {
if (e.message.includes('Unable to deselect')) {
// Single select: use selectOptions instead
if (!select.multiple) {
await user.selectOptions(select, 'different-value')
}
}
}
```
--------------------------------
### Low-Level Keyboard and Pointer APIs
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/INDEX.md
Detailed keyboard and pointer interactions using specific notation.
```typescript
// Keyboard with notation
await user.keyboard('hello')
await user.keyboard('{Control>}a{/Control}') // Ctrl+A
// Pointer with movement and buttons
await user.pointer([{target: element}, '[MouseLeft]'])
await user.pointer('[MouseRight]') // Right-click
```
--------------------------------
### Content Could Not Be Selected Recovery
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/errors.md
Example of how to recover from the 'clear()' error when the element's content cannot be selected.
```typescript
try {
await user.clear(element)
} catch (e) {
if (e.message.includes('could not be selected')) {
// Remove readonly and try again
element.removeAttribute('readonly')
await user.clear(element)
}
}
```
--------------------------------
### pointer() vs hover()
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/pointer.md
Comparison between the low-level pointer API and the convenience hover() method.
```typescript
// Convenience
await user.hover(button)
// Low-level
await user.pointer({target: button})
```
--------------------------------
### userEvent.deselectOptions
Source: https://github.com/testing-library/user-event/blob/main/_autodocs/api-reference/userEvent.md
Simulates deselecting one or more options from a multi-select element. The example shows how to deselect an option using its value.
```typescript
const user = userEvent.setup()
const select = screen.getByRole('listbox')
await user.deselectOptions(select, 'option-value')
```