Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: expose User Event in the exports and website #1410

Merged
merged 4 commits into from
Aug 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/pure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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';
2 changes: 2 additions & 0 deletions src/user-event/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { setup } from './setup';
import { PressOptions } from './press';
import { TypeOptions } from './type';

export { UserEventConfig } from './setup';

export const userEvent = {
setup,

Expand Down
44 changes: 19 additions & 25 deletions website/docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,22 @@ 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)
- [`fireEvent[eventName]`](#fireeventeventname)
- [`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)
Expand All @@ -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)

Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -402,6 +388,10 @@ Convenience methods for common events like: `press`, `changeText`, `scroll`.
fireEvent.press: (element: ReactTestInstance, ...data: Array<any>) => 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
Expand Down Expand Up @@ -434,6 +424,10 @@ expect(onPressMock).toHaveBeenCalledWith(eventData);
fireEvent.changeText: (element: ReactTestInstance, ...data: Array<any>) => 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
Expand Down
41 changes: 30 additions & 11 deletions website/docs/UserEvent.md
Original file line number Diff line number Diff line change
Expand Up @@ -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?: {
Expand All @@ -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()`
Expand All @@ -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()`

Expand All @@ -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
Expand All @@ -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.

Expand All @@ -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`
Expand All @@ -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.

2 changes: 1 addition & 1 deletion website/sidebars.js
Original file line number Diff line number Diff line change
@@ -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',
Expand Down