### Basic Get Query Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/guides/how-to-query.mdx
Demonstrates the basic usage of a `getBy*` query. Use this when you expect exactly one matching element.
```typescript
getByRole();
```
--------------------------------
### Install ESLint Plugin for Testing Library
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/start/quick-start.mdx
Install the recommended ESLint plugin to enforce testing best practices.
```bash
yarn add -D eslint-plugin-testing-library
```
```bash
npm install -D eslint-plugin-testing-library
```
--------------------------------
### Install React Native Testing Library
Source: https://github.com/callstack/react-native-testing-library/blob/main/README.md
Install the library as a development dependency in your project.
```sh
npm install --save-dev @testing-library/react-native
```
--------------------------------
### Render and Get Element by Hint Text
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/queries.mdx
This example shows how to render a component and then use `screen.getByHintText` to find an element with the accessibility hint 'Plays a song'.
```jsx
import { render, screen } from '@testing-library/react-native';
render();
const element = screen.getByHintText('Plays a song');
```
--------------------------------
### Install React Native Testing Library
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/guides/quick-start.md
Install the library using npm, yarn, pnpm, or bun. This command adds the library as a development dependency.
```bash
npm install -D @testing-library/react-native
```
```bash
yarn add -D @testing-library/react-native
```
```bash
pnpm add -D @testing-library/react-native
```
```bash
bun add -D @testing-library/react-native
```
--------------------------------
### Debug output example
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/screen.mdx
Example output format for the debug method.
```jsx
optional message
Press me
```
--------------------------------
### Default View role examples
Source: https://github.com/callstack/react-native-testing-library/wiki/Accessibility-Roles
Examples of View component accessibility configurations and their resulting screen reader behavior.
```jsx
```
```jsx
```
```jsx
```
```jsx
```
--------------------------------
### Render and Get Element by Placeholder Text
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/queries.mdx
This example demonstrates how to render a component and then use `screen.getByPlaceholderText` to find an element with the placeholder 'username'.
```jsx
import { render, screen } from '@testing-library/react-native';
render();
const element = screen.getByPlaceholderText('username');
```
--------------------------------
### Text Matching Examples
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/queries.md
Provides examples of using strings and regular expressions to match text content, including full string matches, substring matches, and case-insensitive matching.
```jsx
await render(Hello World);
```
```js
// Matching a string:
screen.getByText('Hello World'); // full string match
screen.getByText('llo Worl', { exact: false }); // substring match
screen.getByText('hello world', { exact: false }); // ignore case-sensitivity
// Matching a regex:
screen.getByText(/World/); // substring match
screen.getByText(/world/i); // substring match, ignore case
screen.getByText(/^hello world$/i); // full string match, ignore case-sensitivity
screen.getByText(/Hello W?oRlD/i); // advanced regex
```
```js
// substring does not match
screen.getByText('llo Worl');
// full string does not match
screen.getByText('Goodbye World');
// case-sensitive regex with different case
screen.getByText(/hello world/);
```
--------------------------------
### Setup userEvent for Realistic Interactions
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/guides/llm-guidelines.mdx
Initialize the userEvent API for simulating user interactions. This setup is required before using any userEvent methods.
```tsx
const user = userEvent.setup();
```
--------------------------------
### Default Text role examples
Source: https://github.com/callstack/react-native-testing-library/wiki/Accessibility-Roles
Examples of Text component and accessible View configurations for text-based accessibility.
```jsx
Hello
```
```jsx
Hello
```
```jsx
```
```jsx
```
--------------------------------
### Render Options Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/skills/react-native-testing/references/api-reference-v13.md
Illustrates common usage of the `render` function, including basic rendering, rendering with a wrapper component for context providers, and an example of asynchronous rendering with `renderAsync` for React 19/Suspense.
```tsx
import { render, screen, renderAsync } from '@testing-library/react-native';
render();
expect(screen.getByRole('button', { name: 'start' })).toBeOnTheScreen();
// With wrapper
render(, {
wrapper: ({ children }) => {children},
});
// Async (React 19 / Suspense)
await renderAsync();
```
--------------------------------
### Default TextInput role examples
Source: https://github.com/callstack/react-native-testing-library/wiki/Accessibility-Roles
Examples of TextInput component configurations and their impact on screen reader labels and traits.
```jsx
```
```jsx
```
```jsx
```
```jsx
```
--------------------------------
### Install ESLint Plugin
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/guides/quick-start.md
Install the eslint-plugin-testing-library to help avoid common mistakes in Testing Library usage. This command adds the plugin as a development dependency.
```bash
npm install -D eslint-plugin-testing-library
```
```bash
yarn add -D eslint-plugin-testing-library
```
```bash
pnpm add -D eslint-plugin-testing-library
```
```bash
bun add -D eslint-plugin-testing-library
```
--------------------------------
### Install Dependencies with Lockfile
Source: https://github.com/callstack/react-native-testing-library/blob/main/agents/example-apps.md
If dependency resolution issues arise, restore the previous yarn.lock and run yarn install to maintain the existing dependency tree.
```bash
yarn install
```
--------------------------------
### Setup userEvent
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/guides/llm-guidelines.md
Initialize the userEvent object before performing user interactions. This setup is required for all subsequent userEvent methods.
```tsx
const user = userEvent.setup();
```
--------------------------------
### TextMatch Examples: String and Regex Matching
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/queries.mdx
Provides examples of using TextMatch with strings and regular expressions for various matching scenarios, including full string, substring, and case-insensitive matching.
```jsx
render(Hello World);
```
```js
// Matching a string:
screen.getByText('Hello World'); // full string match
screen.getByText('llo Worl', { exact: false }); // substring match
screen.getByText('hello world', { exact: false }); // ignore case-sensitivity
// Matching a regex:
screen.getByText(/World/); // substring match
screen.getByText(/world/i); // substring match, ignore case
screen.getByText(/^hello world$/i); // full string match, ignore case-sensitivity
screen.getByText(/Hello W?oRlD/i); // advanced regex
```
```js
// substring does not match
screen.getByText('llo Worl');
// full string does not match
screen.getByText('Goodbye World');
// case-sensitive regex with different case
screen.getByText(/hello world/);
```
--------------------------------
### Basic screen query example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/screen.md
Demonstrates how to use `screen` to find an element by its role and name after rendering a component.
```jsx
import { render, screen } from '@testing-library/react-native';
test('example', async () => {
await render();
const buttonStart = screen.getByRole('button', { name: 'start' });
});
```
--------------------------------
### Basic and Wrapper Render Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/skills/react-native-testing/references/api-reference-v14.md
Illustrates how to use the `render` function, both for a basic component render and with a `wrapper` option to provide a `ThemeProvider`.
```tsx
import { render, screen } from '@testing-library/react-native';
await render();
expect(screen.getByRole('button', { name: 'start' })).toBeOnTheScreen();
// With wrapper
await render(, {
wrapper: ({ children }) => {children},
});
```
--------------------------------
### Fire changeText Convenience Method Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/fire-event.md
Example of using the fireEvent.changeText convenience method to simulate text input.
```jsx
import { View, TextInput } from 'react-native';
import { render, screen, fireEvent } from '@testing-library/react-native';
const onChangeTextMock = jest.fn();
const CHANGE_TEXT = 'content';
await render(
,
);
await fireEvent.changeText(screen.getByPlaceholderText('Enter data'), CHANGE_TEXT);
```
--------------------------------
### Custom Render Function with Async Setup
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/cookbook/custom-render.md
Implement custom render functions as `async` and use `await render()` to handle asynchronous setup, such as fetching data before rendering the component.
```tsx
async function renderWithData(ui: React.ReactElement) {
const data = await fetchTestData();
return await render({ui});
}
test('renders SomeScreen', async () => {
await renderWithData();
// ...
});
```
--------------------------------
### TextInput Setup with editable={false}
Source: https://github.com/callstack/react-native-testing-library/wiki/TextInput-Events
This setup demonstrates a TextInput component with editable set to false. It includes handlers for various input events.
```javascript
```
--------------------------------
### Fire press Event Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/fire-event.md
Example of using the fireEvent.press convenience method to simulate a press event on a TouchableOpacity.
```jsx
import { View, Text, TouchableOpacity } from 'react-native';
import { render, screen, fireEvent } from '@testing-library/react-native';
const onPressMock = jest.fn();
const eventData = {
nativeEvent: {
pageX: 20,
pageY: 30,
},
};
await render(
Press me
,
);
await fireEvent.press(screen.getByText('Press me'), eventData);
expect(onPressMock).toHaveBeenCalledWith(expect.objectContaining(eventData));
```
--------------------------------
### Use Custom Render Function in Tests
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/cookbook/custom-render.md
Utilize the custom render function in your test files to render components with the predefined setup. This example shows rendering a `WelcomeScreen` with and without a user object.
```tsx
import { screen } from '@testing-library/react-native';
import { renderWithProviders } from '../test-utils';
// ...
test('renders WelcomeScreen with user', async () => {
await renderWithProviders(, { user: { name: 'Jar-Jar' } });
expect(screen.getByText(/hello Jar-Jar/i)).toBeOnTheScreen();
});
test('renders WelcomeScreen without user', async () => {
await renderWithProviders(, { user: null });
expect(screen.getByText(/hello stranger/i)).toBeOnTheScreen();
});
```
--------------------------------
### Basic Query Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/guides/how-to-query.md
Demonstrates the basic structure of a query, separating the variant and predicate.
```typescript
getByRole();
```
--------------------------------
### Multi-line TextInput Component Setup
Source: https://github.com/callstack/react-native-testing-library/wiki/TextInput-Events
A standard TextInput configuration with multi-line support and various event handlers attached.
```jsx
```
--------------------------------
### Update Dependencies (Alternative Command)
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/guides/migration-v14.md
An alternative command for updating dependencies, often used in conjunction with installing packages. Ensure to run the install command afterward.
```bash
npx codemod@latest rntl-v14-update-deps
npm install
```
```bash
yarn dlx codemod@latest rntl-v14-update-deps
yarn install
```
```bash
pnpm dlx codemod@latest rntl-v14-update-deps
pnpm install
```
```bash
bunx codemod@latest rntl-v14-update-deps
bun install
```
--------------------------------
### renderHookAsync Usage Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/misc/render-hook.mdx
Example demonstrating the usage of renderHookAsync to test a hook with asynchronous operations. It shows how to wait for async operations and re-render the hook.
```APIDOC
## renderHookAsync
### Description
Use `renderHookAsync` to test hooks that involve asynchronous operations, such as data fetching, timers, or concurrent React features. It returns an object with the hook's result and methods to manage its lifecycle asynchronously.
### Usage
```ts
import { renderHookAsync, act } from '@testing-library/react-native';
// Assuming useAsyncHook is a custom hook with async behavior
const { result, rerenderAsync } = await renderHookAsync(useAsyncHook);
// Test initial state
expect(result.current.loading).toBe(true);
// Wait for async operation to complete (example using setTimeout)
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 100));
});
// Re-render to get updated state after async operation
await rerenderAsync();
expect(result.current.loading).toBe(false);
```
### When to Use
`renderHookAsync` is recommended for hooks that utilize React Suspense, `React.use()`, or other concurrent rendering features where precise control over re-render timing is crucial.
```
--------------------------------
### getAllBy* Query Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/queries.md
Use getAllBy* queries to find an array of all matching elements. Throws an error if no elements match.
```ts
getAllByX(...): TestInstance[]
```
--------------------------------
### Install Test Renderer
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/guides/quick-start.md
Install the Test Renderer peer dependency using npm, yarn, pnpm, or bun. This is required for compatibility with React 19 and improved type safety.
```bash
npm install -D test-renderer
```
```bash
yarn add -D test-renderer
```
```bash
pnpm add -D test-renderer
```
```bash
bun add -D test-renderer
```
--------------------------------
### renderHook Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/skills/react-native-testing/references/api-reference-v13.md
Demonstrates basic usage of renderHook to test a custom hook's initial state and state updates triggered by act.
```tsx
const { result } = renderHook(() => useCount());
expect(result.current.count).toBe(0);
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
```
--------------------------------
### Example `useCount` hook implementation
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/render-hook.md
A basic implementation of a `useCount` hook that manages a count state and provides an increment function.
```javascript
// useCount.js
import { useState } from 'react';
export const useCount = () => {
const [count, setCount] = useState(0);
const increment = () => setCount((previousCount) => previousCount + 1);
return { count, increment };
};
```
--------------------------------
### Generate Expo Cookbook App
Source: https://github.com/callstack/react-native-testing-library/blob/main/agents/example-apps.md
Use this command to generate a new Expo app from a router-enabled template for the cookbook example.
```bash
yarn create expo-app /tmp/rntl-cookbook-fresh --example with-router --yes
```
--------------------------------
### Sync act warning example
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/advanced/understanding-act.mdx
The standard pattern for wrapping state-updating code to resolve synchronous act warnings.
```javascript
act(() => {
/* fire events that update state */
});
/* assert on the output */
```
--------------------------------
### SectionList Component Setup
Source: https://github.com/callstack/react-native-testing-library/wiki/ScrollView-Events
Configuration for a SectionList component including various scroll and content event handlers.
```jsx
item + index}
renderSectionHeader={renderSectionHeader}
renderItem={renderItem}
onContentSizeChange={handleContentSizeChange}
onMomentumScrollBegin={handleMomentumScrollBegin}
onMomentumScrollEnd={handleMomentumScrollEnd}
onScroll={handleScroll}
onScrollBeginDrag={handleScrollBeginDrag}
onScrollEndDrag={handleScrollEndDrag}
onScrollToTop={handleScrollToTop}
onEndReached={handleEndReached}
/>
```
--------------------------------
### queryAllBy* Query Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/queries.md
Use queryAllBy* queries to find an array of all matching nodes. Returns an empty array if no elements match.
```ts
queryAllByX(...): TestInstance[]
```
--------------------------------
### ScrollView component setup
Source: https://github.com/callstack/react-native-testing-library/wiki/ScrollView-Events
Configures a ScrollView with common event handlers and scroll behavior properties.
```jsx
```
--------------------------------
### setup()
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/user-event.md
Creates a User Event object instance, which can be used to trigger events. Options include controlling the delay between events and a utility for advancing timers.
```APIDOC
## setup()
### Description
Creates a User Event object instance, which can be used to trigger events.
### Signature
```ts
userEvent.setup(options?: {
delay?: number;
advanceTimers?: (delay: number) => Promise | void;
})
```
### Options
- `delay` controls the default delay between subsequent events, e.g., keystrokes.
- `advanceTimers` is a time advancement utility function that should be used for fake timers. The default setup handles both real timers and Jest fake timers.
```
--------------------------------
### Render and Get Element by Text
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/queries.mdx
This example demonstrates rendering a component and then using `screen.getByText` to find an element containing the text 'banana'.
```jsx
import { render, screen } from '@testing-library/react-native';
render();
const element = screen.getByText('banana');
```
--------------------------------
### userEvent.setup()
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/events/user-event.mdx
Creates a User Event object instance used to trigger realistic user interactions.
```APIDOC
## userEvent.setup()
### Description
Creates a User Event object instance, which can be used to trigger events.
### Parameters
#### Request Body
- **options** (object) - Optional - Configuration object containing:
- **delay** (number) - Controls the default delay between subsequent events.
- **advanceTimers** (function) - A time advancement utility function for fake timers.
### Request Example
const user = userEvent.setup();
```
--------------------------------
### Example `act()` warning in console
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/guides/understanding-act.md
This is a typical warning logged to the console when an update to a component inside a test is not wrapped in `act()`.
```text
An update to Root inside a test was not wrapped in act(...).
When testing, code that causes React state updates should be wrapped into act(...):
act(() => {
/* fire events that update state */
});
/* assert on the output */
This ensures that you're testing the behavior the user would see in the browser.
Learn more at https://react.dev/link/wrap-tests-with-act
```
--------------------------------
### Render and Get Element by Test ID
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/queries.mdx
This example demonstrates rendering a component and then using `screen.getByTestId` to find an element with the test ID 'unique-id'.
```jsx
import { render, screen } from '@testing-library/react-native';
render();
const element = screen.getByTestId('unique-id');
```
--------------------------------
### Awaiting act Callback
Source: https://github.com/callstack/react-native-testing-library/blob/main/skills/react-native-testing/references/api-reference-v14.md
Example of awaiting the `act` function, which is required in v14 even for synchronous callbacks that trigger state updates.
```tsx
await act(() => {
result.current.increment();
});
```
--------------------------------
### Render and Get Element by Display Value
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/queries.mdx
This example shows rendering a component and then using `screen.getByDisplayValue` to locate an element that has the display value 'username'.
```jsx
import { render, screen } from '@testing-library/react-native';
render();
const element = screen.getByDisplayValue('username');
```
--------------------------------
### User Event Setup
Source: https://github.com/callstack/react-native-testing-library/blob/main/skills/react-native-testing/references/api-reference-v13.md
Initializes the User Event API, which simulates realistic user interactions. Options include setting a delay between events or customizing timer advancement.
```APIDOC
## User Event
Prefer `userEvent` over `fireEvent`. User Event simulates realistic interaction sequences on **host elements only**, with proper event data.
### Setup
```ts
const user = userEvent.setup(options?: { delay?: number; advanceTimers?: (delay: number) => Promise | void });
```
```
--------------------------------
### Setup User Event Instance
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/events/user-event.mdx
Creates a User Event object instance for triggering events. Options include controlling delay between events and advancing timers.
```typescript
userEvent.setup(options?: {
delay: number;
advanceTimers: (delay: number) => Promise | void;
})
```
```typescript
const user = userEvent.setup();
```
--------------------------------
### Fire changeText Event Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/fire-event.md
Example of using fireEvent to trigger a 'onChangeText' event on a TextInput component.
```jsx
import { render, screen, fireEvent } from '@testing-library/react-native';
test('fire changeText event', async () => {
const onEventMock = jest.fn();
await render(
// MyComponent renders TextInput which has a placeholder 'Enter details'
// and with `onChangeText` bound to handleChangeText
,
);
await fireEvent(screen.getByPlaceholderText('change'), 'onChangeText', 'ab');
expect(onEventMock).toHaveBeenCalledWith('ab');
});
```
--------------------------------
### Testing hook with `initialProps` and `rerender`
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/render-hook.md
Demonstrates how to use `initialProps` to set up a hook with specific starting values and how to use the `rerender` function to update those props.
```typescript
import { useState, useEffect } from 'react';
import { renderHook, act } from '@testing-library/react-native';
const useCount = (initialCount: number) => {
const [count, setCount] = useState(initialCount);
const increment = () => setCount((previousCount) => previousCount + 1);
useEffect(() => {
setCount(initialCount);
}, [initialCount]);
return { count, increment };
};
it('should increment count', async () => {
const { result, rerender } = await renderHook((initialCount: number) => useCount(initialCount), {
initialProps: 1,
});
expect(result.current.count).toBe(1);
await act(() => {
result.current.increment();
});
expect(result.current.count).toBe(2);
await rerender(5);
expect(result.current.count).toBe(5);
});
```
--------------------------------
### User Sign-in Test with Async Events
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/cookbook/async-events.md
Example test demonstrating a user sign-in flow, utilizing async operations and assertions for elements appearing and disappearing.
```javascript
test('User can sign in with correct credentials', async () => {
// Typical test setup
const user = userEvent.setup();
await render();
// No need to use async here, components are already rendered
expect(screen.getByRole('header', { name: 'Sign in to Hello World App!' })).toBeOnTheScreen();
// Using await as User Event requires it
await user.type(screen.getByLabelText('Username'), 'admin');
await user.type(screen.getByLabelText('Password'), 'admin1');
await user.press(screen.getByRole('button', { name: 'Sign In' }));
// Using await as sign in operation is asynchronous
expect(await screen.findByRole('header', { name: 'Welcome admin!' })).toBeOnTheScreen();
// Follow-up assertions do not need to be async, as we already waited for sign in operation to complete
expect(
screen.queryByRole('header', { name: 'Sign in to Hello World App' }),
).not.toBeOnTheScreen();
expect(screen.queryByLabelText('Username')).not.toBeOnTheScreen();
expect(screen.queryByLabelText('Password')).not.toBeOnTheScreen();
});
```
--------------------------------
### Install Test Renderer
Source: https://github.com/callstack/react-native-testing-library/blob/main/README.md
Install Test Renderer as a dev dependency, as it is a peer dependency for React Native Testing Library.
```sh
npm install --save-dev test-renderer
```
--------------------------------
### Fire Native Event Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/fire-event.md
Example of using fireEvent to trigger a native event like 'blur' which is not aliased by default convenience methods.
```jsx
import { TextInput, View } from 'react-native';
import { fireEvent, render, screen } from '@testing-library/react-native';
const onBlurMock = jest.fn();
await render(
,
);
// you can omit the `on` prefix
await fireEvent(screen.getByPlaceholderText('my placeholder'), 'blur');
```
--------------------------------
### configure()
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/misc/config.mdx
Configures global settings for React Native Testing Library.
```APIDOC
## configure(options)
### Description
Sets global configuration options for the library.
### Parameters
#### Request Body
- **asyncUtilTimeout** (number) - Optional - Default timeout in ms for async helpers.
- **defaultHidden** (boolean) - Optional - Default value for includeHiddenElements query option.
- **defaultDebugOptions** (Partial) - Optional - Default options for debug() calls.
- **concurrentRoot** (boolean) - Optional - Enables or disables concurrent rendering.
### Request Example
{
"asyncUtilTimeout": 2000,
"defaultHidden": true
}
```
--------------------------------
### Managed TextInput Component Setup
Source: https://github.com/callstack/react-native-testing-library/wiki/TextInput-Events
This JSX code defines a TextInput component with various event handlers and properties. It serves as the setup for observing event outputs.
```jsx
```
--------------------------------
### Setup User Event Instance
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/user-event.md
Creates a User Event object instance, which can be used to trigger events. The 'delay' option controls the default delay between subsequent events, and 'advanceTimers' is a utility for fake timers.
```typescript
userEvent.setup(options?: {
delay?: number;
advanceTimers?: (delay: number) => Promise | void;
})
```
```typescript
const user = userEvent.setup();
```
--------------------------------
### Accessing Queries using screen Object
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/queries.mdx
Demonstrates how to use the `screen` object to access query functions. This is the recommended approach for accessing queries as it automatically binds them to the most recently rendered UI.
```tsx
import { render, screen } from '@testing-library/react-native';
test('accessing queries using "screen" object', () => {
render(...);
screen.getByRole("button", { name: "Start" });
})
```
--------------------------------
### Global MSW Server Setup for Jest
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/cookbook/network-requests.md
Configures Mock Service Worker (MSW) to run globally before all tests and reset handlers after each test. This setup ensures all API requests are handled or warned if unmocked.
```ts
// Enable API mocking via Mock Service Worker (MSW)
beforeAll(() => server.listen());
// Reset any runtime request handlers we may add during the tests
afterEach(() => server.resetHandlers());
// Disable API mocking after the tests are done
afterAll(() => server.close());
// ... rest of your setup file
```
--------------------------------
### screen.debug
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/screen.mdx
Pretty prints the rendered component tree.
```APIDOC
## debug(options)
### Description
Pretty prints deeply rendered component passed to render.
### Parameters
- **options** (Object) - Optional
- **message** (string) - Optional - Message to print on top.
- **mapProps** (Function) - Optional - Function to transform props before printing.
```
--------------------------------
### React Native Component Test Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/README.md
Example demonstrating how to test a React Native form component using RNTL. It simulates user interactions like typing and pressing buttons, and asserts the expected form submission data.
```jsx
import { render, screen, userEvent } from '@testing-library/react-native';
import { QuestionsBoard } from '../QuestionsBoard';
test('form submits two answers', async () => {
const questions = ['q1', 'q2'];
const onSubmit = jest.fn();
const user = userEvent.setup();
await render();
const answerInputs = screen.getAllByLabelText('answer input');
// simulates the user focusing on TextInput and typing text one char at a time
await user.type(answerInputs[0], 'a1');
await user.type(answerInputs[1], 'a2');
// simulates the user pressing on any pressable element
await user.press(screen.getByRole('button', { name: 'Submit' }));
expect(onSubmit).toHaveBeenCalledWith({
1: { q: 'q1', a: 'a1' },
2: { q: 'q2', a: 'a2' },
});
});
```
--------------------------------
### Install Test Renderer Package
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/guides/migration-v14.md
Remove react-test-renderer and its types, then install the appropriate test-renderer version based on your React minor version. Use test-renderer@1.2 for React 19.2, test-renderer@1.1 for React 19.1, and test-renderer@1.0 for React 19.0.
```bash
npm uninstall react-test-renderer @types/react-test-renderer
npm install -D test-renderer@1.2
```
```bash
yarn remove react-test-renderer @types/react-test-renderer
yarn add -D test-renderer@1.2
```
```bash
pnpm remove react-test-renderer @types/react-test-renderer
pnpm add -D test-renderer@1.2
```
```bash
bun remove react-test-renderer @types/react-test-renderer
bun add -D test-renderer@1.2
```
--------------------------------
### Basic Render Test
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/render.md
A simple test case demonstrating how to use the `render` function to render a component and query for an element using `screen`.
```jsx
import { render, screen } from '@testing-library/react-native';
test('basic test', async () => {
await render();
expect(screen.getAllByRole('button', { name: 'start' })).toBeOnTheScreen();
});
```
--------------------------------
### Debug with mapProps
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/screen.mdx
Example of filtering props during debug output.
```jsx
render();
screen.debug({ mapProps: ({ style, ...props }) => ({ props }) });
```
--------------------------------
### queryBy* Query Example
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/queries.md
Use queryBy* queries to find the first matching node or null if no elements match. Use these to assert that an element is not present. Throws if more than one match is found.
```ts
queryByX(...): TestInstance | null
```
--------------------------------
### Debug with message
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/screen.mdx
Example of using the debug method with an optional message.
```jsx
render();
screen.debug({ message: 'optional message' });
```
--------------------------------
### Custom Render Function with Providers
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/cookbook/basics/custom-render.md
Encapsulates common setup steps like providing user and theme contexts within a reusable render function. This is useful for tests requiring consistent context across multiple components.
```tsx
// ...
interface RenderWithProvidersProps {
user?: User | null;
theme?: Theme;
}
export function renderWithProviders(
ui: React.ReactElement,
options?: RenderWithProvidersProps,
) {
return render(
{ui}
,
);
}
```
--------------------------------
### Debug by removing props
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/screen.mdx
Example of removing specific props from debug output.
```ts
screen.debug({ mapProps: ({ path, ...props }) => ({ ...props }) });
```
--------------------------------
### User Sign-in with Async Test
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/cookbook/basics/async-tests.md
Demonstrates an asynchronous test for user sign-in, utilizing the User Event API and awaiting asynchronous operations.
```javascript
test('User can sign in with correct credentials', async () => {
// Typical test setup
const user = userEvent.setup();
render();
// No need to use async here, components are already rendered
expect(screen.getByRole('header', { name: 'Sign in to Hello World App!' })).toBeOnTheScreen();
// Using await as User Event requires it
await user.type(screen.getByLabelText('Username'), 'admin');
await user.type(screen.getByLabelText('Password'), 'admin1');
await user.press(screen.getByRole('button', { name: 'Sign In' }));
// Using await as sign in operation is asynchronous
expect(await screen.findByRole('header', { name: 'Welcome admin!' })).toBeOnTheScreen();
// Follow-up assertions do not need to be async, as we already waited for sign in operation to complete
expect(
screen.queryByRole('header', { name: 'Sign in to Hello World App' }),
).not.toBeOnTheScreen();
expect(screen.queryByLabelText('Username')).not.toBeOnTheScreen();
expect(screen.queryByLabelText('Password')).not.toBeOnTheScreen();
});
```
--------------------------------
### Perform async rerender
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/screen.mdx
Example usage of rerenderAsync for React 19 and Suspense compatibility.
```jsx
import { renderAsync, screen } from '@testing-library/react-native';
test('async rerender test', async () => {
await renderAsync();
await screen.rerenderAsync();
expect(screen.getByText('updated')).toBeOnTheScreen();
});
```
--------------------------------
### Mocking Network Requests with MSW
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/cookbook/network-requests.md
This snippet demonstrates how to set up MSW to mock network requests for the random user API. It includes defining handlers, setting up the server, and managing the server's lifecycle during tests.
```tsx
import { render, screen, waitForElementToBeRemoved } from '@testing-library/react-native';
import React from 'react';
import PhoneBook from '../PhoneBook';
import { User } from '../types';
import {http, HttpResponse} from "msw";
import {setupServer} from "msw/node";
// Define request handlers and response resolvers for random user API.
// By default, we always return the happy path response.
const handlers = [
http.get('https://randomuser.me/api/*', () => {
return HttpResponse.json(DATA);
}),
];
// Setup a request interception server with the given request handlers.
const server = setupServer(...handlers);
// Enable API mocking via Mock Service Worker (MSW)
beforeAll(() => server.listen());
// Reset any runtime request handlers we may add during the tests
afterEach(() => server.resetHandlers());
// Disable API mocking after the tests are done
afterAll(() => server.close());
describe('PhoneBook', () => {
it('fetches all contacts and favorites successfully and renders lists in sections correctly', async () => {
await render();
await waitForElementToBeRemoved(() => screen.getByText(/users data not quite there yet/i));
expect(await screen.findByText('Name: Mrs Ida Kristensen')).toBeOnTheScreen();
expect(await screen.findByText('Email: ida.kristensen@example.com')).toBeOnTheScreen();
expect(await screen.findAllByText(/name/i)).toHaveLength(3);
expect(await screen.findByText(/my favorites/i)).toBeOnTheScreen();
expect(await screen.findAllByLabelText('favorite-contact-avatar')).toHaveLength(3);
});
});
const DATA: { results: User[] } = {
results: [
{
name: {
title: 'Mrs',
first: 'Ida',
last: 'Kristensen',
},
email: 'ida.kristensen@example.com',
id: {
name: 'CPR',
value: '250562-5730',
},
picture: {
large: 'https://randomuser.me/api/portraits/women/26.jpg',
medium: 'https://randomuser.me/api/portraits/med/women/26.jpg',
thumbnail: 'https://randomuser.me/api/portraits/thumb/women/26.jpg',
},
cell: '123-4567-890',
},
// For brevity, we have omitted the rest of the users, you can still find them in
// examples/cookbook/app/network-requests/__tests__/test-utils.ts
...
],
};
```
--------------------------------
### Debug with flattened styles
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/docs/api/screen.mdx
Example of transforming prop values like flattening styles during debug.
```ts
import { StyleSheet } from 'react-native';
screen.debug({ mapProps : {({ style, ...props })} => ({ style : StyleSheet.flatten(style), ...props }) });
```
--------------------------------
### Define expanded accessibility state
Source: https://github.com/callstack/react-native-testing-library/wiki/Accessibility:-State
Examples of using accessibilityState with the expanded property for menu roles.
```jsx
```
```jsx
```
```jsx
```
```jsx
```
```jsx
```
```jsx
```
--------------------------------
### Jotai Atoms and Store Setup
Source: https://github.com/callstack/react-native-testing-library/blob/main/website/docs/13.x/cookbook/state-management/jotai.md
Defines Jotai atoms for tasks and new task titles, and sets up a store for external state management. Use this for managing global state.
```tsx
import { atom, createStore } from 'jotai';
import { Task } from './types';
export const tasksAtom = atom([]);
export const newTaskTitleAtom = atom('');
// Available for use outside React components
export const store = createStore();
// Selectors
export function getAllTasks(): Task[] {
return store.get(tasksAtom);
}
// Actions
export function addTask(task: Task) {
store.set(tasksAtom, [...getAllTasks(), task]);
}
```
--------------------------------
### Define disabled accessibility state
Source: https://github.com/callstack/react-native-testing-library/wiki/Accessibility:-State
Examples of using accessibilityState with the disabled property for button roles.
```jsx
```
```jsx
```
```jsx
```
```jsx
```
```jsx
```
--------------------------------
### Using `exact: false` for Fuzzy Matching
Source: https://github.com/callstack/react-native-testing-library/blob/main/docs/api/queries.md
Demonstrates how to use the `exact: false` option to perform substring and case-insensitive matching when searching for text.
```js
screen.getByText('llo Worl', { exact: false }); // substring match
screen.getByText('hello world', { exact: false }); // ignore case-sensitivity
```