CodeBlanks Logo Icon CodeBlanks

fireEvent

Learn to trigger events with fireEvent.

What is fireEvent?

fireEvent is the RNTL function that simulates user events in a test. fireEvent.press(element) simulates a button press, fireEvent.changeText(element, 'text') simulates text input. It lets you test how a component reacts.

Typical flow: render the component with render, find a button with getByText, press it with fireEvent.press, and assert the result with expect. This does what a real user does, in a test environment. fireEvent runs synchronously; when the handler finishes the render updates. For async work waitFor is needed.

Practice Press with fireEvent

An App component is already defined; it holds a button and a counter. Render with render(<App />). Find the button with getByText('Up'). Press with fireEvent.press. Check the result with getByText('1').

Starter code

App.js
// Import render and fireEvent

// Write a test named 'count goes up on press'
// render App, find 'Up' button with getByText, press with fireEvent.press, check '1' with getByText

Sample solution

App.js
import { render, fireEvent } from "@testing-library/react-native";
import { Button, Text, View } from "react-native";
import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);
  return (
    <View>
      <Text>{count}</Text>
      <Button title="Up" onPress={() => setCount(count + 1)} />
    </View>
  );
}

test("count goes up on press", () => {
  const { getByText } = render(<App />);
  fireEvent.press(getByText("Up"));
  expect(getByText("1")).toBeTruthy();
});

The press event

fireEvent.press(element) sends a press event to an element. It works on any component with an onPress prop: Button, TouchableOpacity, Pressable. The element is found with getByText or getByTestId.

The press event calls the onPress handler; state updates and the render refreshes. The next getByText call sees the new state. fireEvent.changeText simulates text input on a TextInput; it runs the onChangeText handler. Each event type has its own method: fireEvent.scroll, fireEvent.focus and more. Picking the right method keeps the test realistic.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does fireEvent do?

App.js
fireEvent.press(button);
  • Styles a component
  • Simulates user events Correct answer
  • Stores data
  • Sends network requests

Explanation: fireEvent simulates user events.

2 The fireEvent call

Question
fireEvent.____(button);
Answer
fireEvent.press(button);

Explanation: fireEvent.press simulates a press.

3 Match each event to its role

Term Meaning
fireEvent.press Presses a button
fireEvent.changeText Types text
fireEvent.scroll Scrolls
fireEvent.focus Focuses

All lessons in Intermediate