diff --git a/src/pure.ts b/src/pure.ts index 8752aa9c8..3f9c99381 100644 --- a/src/pure.ts +++ b/src/pure.ts @@ -14,6 +14,7 @@ export { export { getDefaultNormalizer } from './matches'; export { renderHook } from './renderHook'; export { screen } from './screen'; +export { userEvent } from './user-event'; export type { RenderOptions, @@ -23,3 +24,4 @@ export type { } from './render'; export type { RenderHookOptions, RenderHookResult } from './renderHook'; export type { Config } from './config'; +export type { UserEventConfig } from './user-event'; diff --git a/src/user-event/index.ts b/src/user-event/index.ts index c3895e281..dca1719e9 100644 --- a/src/user-event/index.ts +++ b/src/user-event/index.ts @@ -3,6 +3,8 @@ import { setup } from './setup'; import { PressOptions } from './press'; import { TypeOptions } from './type'; +export { UserEventConfig } from './setup'; + export const userEvent = { setup, diff --git a/website/docs/API.md b/website/docs/API.md index f992c46d6..c1911ae54 100644 --- a/website/docs/API.md +++ b/website/docs/API.md @@ -7,20 +7,13 @@ title: API - [`render`](#render) - [`render` options](#render-options) - - [`wrapper` option](#wrapper-option) - - [`createNodeMock` option](#createnodemock-option) - - [`unstable_validateStringsRenderedWithinText` option](#unstable_validatestringsrenderedwithintext-option) - [`...queries`](#queries) - - [Example](#example) - [`update`](#update) - [`unmount`](#unmount) - [`debug`](#debug) - - [`message` option](#message-option) - - [`mapProps` option](#mapprops-option) - - [`debug.shallow`](#debugshallow) - [`toJSON`](#tojson) - [`root`](#root) - - [`UNSAFE_root`](#unsafe_root) + - [`UNSAFE_root`](#unsaferoot) - [`screen`](#screen) - [`cleanup`](#cleanup) - [`fireEvent`](#fireevent) @@ -28,10 +21,8 @@ title: API - [`fireEvent.press`](#fireeventpress) - [`fireEvent.changeText`](#fireeventchangetext) - [`fireEvent.scroll`](#fireeventscroll) - - [On a `ScrollView`](#on-a-scrollview) - - [On a `FlatList`](#on-a-flatlist) - [`waitFor`](#waitfor) - - [Using Jest fake timers](#using-jest-fake-timers) + - [Using a React Native version \< 0.71 with Jest fake timers](#using-a-react-native-version--071-with-jest-fake-timers) - [`waitForElementToBeRemoved`](#waitforelementtoberemoved) - [`within`, `getQueriesForElement`](#within-getqueriesforelement) - [`queryBy*` APIs](#queryby-apis) @@ -40,24 +31,12 @@ title: API - [`renderHook`](#renderhook) - [`callback`](#callback) - [`options` (Optional)](#options-optional) - - [`initialProps`](#initialprops) - - [`wrapper`](#wrapper) - [`RenderHookResult` object](#renderhookresult-object) - - [`result`](#result) - - [`rerender`](#rerender) - - [`unmount`](#unmount-1) - [Examples](#examples) - - [With `initialProps`](#with-initialprops) - - [With `wrapper`](#with-wrapper) - [Configuration](#configuration) - [`configure`](#configure) - - [`asyncUtilTimeout` option](#asyncutiltimeout-option) - - [`defaultIncludeHiddenElements` option](#defaultincludehiddenelements-option) - - [`defaultDebugOptions` option](#defaultdebugoptions-option) - [`resetToDefaults()`](#resettodefaults) - [Environment variables](#environment-variables) - - [`RNTL_SKIP_AUTO_CLEANUP`](#rntl_skip_auto_cleanup) - - [`RNTL_SKIP_AUTO_DETECT_FAKE_TIMERS`](#rntl_skip_auto_detect_fake_timers) - [Accessibility](#accessibility) - [`isHiddenFromAccessibility`](#ishiddenfromaccessibility) @@ -346,9 +325,16 @@ function fireEvent( ): void {} ``` -Fires native-like event with data. +:::note +For common events like `press` or `type` it's recommended to use [User Event API](UserEvent.md) as it offers +more realistic event simulation by emitting a sequence of events with proper event objects that mimic React Native runtime behavior. + +Use Fire Event for cases not supported by User Event and for triggering event handlers on composite components. +::: -Invokes a given event handler (whether native or custom) on the element, bubbling to the root of the rendered tree. +`fireEvent` API allows you to trigger all kind of event handlers on both host and composite components. It will try to invoke a single event handler traversing the component tree bottom-up from passed element and trying to find enabled event handler named `onXxx` when `xxx` is the name of the event passed. + +Unlike User Event, this API does not automatically pass event object to event handler, this is responsibility of the user to construct such object. ```jsx import { render, screen, fireEvent } from '@testing-library/react-native'; @@ -402,6 +388,10 @@ Convenience methods for common events like: `press`, `changeText`, `scroll`. fireEvent.press: (element: ReactTestInstance, ...data: Array) => void ``` +:::note +It is recommended to use the User Event [`press()`](UserEvent.md#press) helper instead as it offers more realistic simulation of press interaction, including pressable support. +::: + Invokes `press` event handler on the element or parent element in the tree. ```jsx @@ -434,6 +424,10 @@ expect(onPressMock).toHaveBeenCalledWith(eventData); fireEvent.changeText: (element: ReactTestInstance, ...data: Array) => void ``` +:::note +It is recommended to use the User Event [`type()`](UserEvent.md#type) helper instead as it offers more realistic simulation of text change interaction, including key-by-key typing, element focus, and other editing events. +::: + Invokes `changeText` event handler on the element or parent element in the tree. ```jsx diff --git a/website/docs/UserEvent.md b/website/docs/UserEvent.md index 0c342aae5..55178e351 100644 --- a/website/docs/UserEvent.md +++ b/website/docs/UserEvent.md @@ -5,16 +5,31 @@ title: User Event ### Table of contents -- [`userEvent.setup`](#usereventsetup) +- [Comparison with Fire Event API](#comparison-with-fire-event-api) +- [`setup()`](#setup) - [Options](#options) - [`press()`](#press) - [`longPress()`](#longpress) + - [Options](#options-1) - [`type()`](#type) - - [Options:](#options-1) + - [Options](#options-2) - [Sequence of events](#sequence-of-events) +:::caution +User Event API is in beta stage. -## `userEvent.setup` +This means that we plan to keep the public API signatures to remain stable, but we might introduce breaking behavioural changes, e.g. changing the ordering or timing of emitted events, without a major version update. Hopefully, well written code should not rely on such specific details. +::: + +## Comparison with Fire Event API + +Fire Event is our original event simulation API. It offers ability to invoke **any event handler** declared on **either host or composite elements**. If the element does not have `onEventName` event handler for passed `eventName` event, or the element is disabled, Fire Event will traverse up the component tree, looking for event handler on both host and composite elements along the way. By default it will **not pass any event data**, but the user might provide it in the last argument. + +In contrast, User Event provides realistic event simulation for main user interactions like `press` or `type`. Each of the interactions will trigger a **sequence of events** corresponding to React Native runtime behavior. These events will be invoked **only on host elements**, and **will automatically receive event data** corresponding to each event. + +If User Event supports given interaction you should always prefer it over Fire Event counterpart, as it will make your tests much more realistic and hence reliable. In other cases, e.g. when event is not supported by User Event, or when invoking event handlers on composite elements, you have to use Fire Event as the only available option. + +## `setup()` ```ts userEvent.setup(options?: { @@ -28,11 +43,11 @@ Example const user = userEvent.setup(); ``` -Creates User Event instances which can be used to trigger events. +Creates an User Event object instance which can be used to trigger events. ### Options -- `delay` - controls the default delay between subsequent events, e.g. keystrokes, etc. -- `advanceTimers` - time advancement utility function that should be used for fake timers. The default setup handles both real and Jest fake timers. +- `delay` - controls the default delay between subsequent events, e.g. keystrokes. +- `advanceTimers` - time advancement utility function that should be used for fake timers. The default setup handles both real timers and Jest fake timers. ## `press()` @@ -49,7 +64,7 @@ const user = userEvent.setup(); await user.press(element); ``` -This helper simulates a press on any pressable element, e.g. `Pressable`, `TouchableOpacity`, `Text`, `TextInput`, etc. Unlike `fireEvent.press()` which is a simpler API that will only call the `onPress` prop, this simulates the entire press event in a more realistic way by reproducing what really happens when a user presses an interface view. This will trigger additional events like `pressIn` and `pressOut`. +This helper simulates a press on any pressable element, e.g. `Pressable`, `TouchableOpacity`, `Text`, `TextInput`, etc. Unlike `fireEvent.press()` which is a simpler API that will only call the `onPress` prop, this function simulates the entire press interaction in a more realistic way by reproducing event sequence emitted by React Native runtime. This helper will trigger additional events like `pressIn` and `pressOut`. ## `longPress()` @@ -68,6 +83,9 @@ await user.longPress(element); Simulates a long press user interaction. In React Native the `longPress` event is emitted when the press duration exceeds long press threshold (by default 500 ms). In other aspects this actions behaves similar to regular `press` action, e.g. by emitting `pressIn` and `pressOut` events. The press duration is customisable through the options. This should be useful if you use the `delayLongPress` prop. When using real timers this will take 500 ms so it is highly recommended to use that API with fake timers to prevent test taking a long time to run. +### Options +- `duration` - duration of the press in miliseconds. Default value is 500 ms. + ## `type()` ```ts @@ -90,7 +108,7 @@ This helper simulates user focusing on `TextInput` element, typing `text` one ch This function supports only host `TextInput` elements. Passing other element type will result in throwing error. -### Options: +### Options - `skipPress` - if true, `pressIn` and `pressOut` events will not be triggered. - `submitEditing` - if true, `submitEditing` event will be triggered after typing the text. @@ -100,14 +118,14 @@ The sequence of events depends on `multiline` prop, as well as passed options. Events will not be emitted if `editable` prop is set to `false`. -Entering the element: +**Entering the element**: - `pressIn` (optional) - `focus` - `pressOut` (optional) The `pressIn` and `pressOut` events are sent by default, but can be skipped by passing `skipPress: true` option. -Typing (for each character): +**Typing (for each character)**: - `keyPress` - `textInput` (optional) - `change` @@ -116,9 +134,10 @@ Typing (for each character): The `textInput` event is sent only for mutliline text inputs. -Leaving the element: +**Leaving the element**: - `submitEditing` (optional) - `endEditing` - `blur` The `submitEditing` event is skipped by default. It can sent by setting `submitEditing: true` option. + diff --git a/website/sidebars.js b/website/sidebars.js index 1df46b141..b9aa3e275 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -1,7 +1,7 @@ module.exports = { docs: { Introduction: ['getting-started', 'faq'], - 'API Reference': ['api', 'api-queries'], + 'API Reference': ['api', 'api-queries', 'user-event'], Guides: [ 'troubleshooting', 'how-should-i-query',