Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Simulating User Interactions | Testing with Jest and React Testing Library
Testing React Apps with Jest and React Testing Library

bookSimulating User Interactions

When you are testing React components, it is essential to verify that user interactions trigger the expected behavior and state changes. React Testing Library provides utilities to simulate these interactions, allowing you to test how your components respond to user actions such as clicks, typing, or form submissions.

Suppose you have a simple button that updates a counter when clicked. To test this interaction, you can use either fireEvent or userEvent from React Testing Library. Here is an example of how you might write a test for a button click that updates component state:

Counter.jsx

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

Counter.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./Counter";

test("increments counter when button is clicked", async () => {
  const user = userEvent.setup();
  render(<Counter />);

  expect(screen.getByText("Count: 0")).toBeInTheDocument();

  await user.click(
    screen.getByRole("button", { name: /increment/i })
  );

  expect(screen.getByText("Count: 1")).toBeInTheDocument();
});

In this test, you render the Counter component, simulate a click on the increment button, and then assert that the displayed count has changed. This pattern helps ensure your UI behaves as expected in response to user events.

After simulating a user interaction, you should always assert that the DOM reflects the expected changes. This means checking for the presence or content of elements that should be updated as a result of the event. For instance, after clicking a button, you might expect a new message to appear, a value to increment, or a form field to clear. Using queries like getByText, queryByRole, or getByLabelText allows you to assert these changes and confirm your component is responding correctly to user input.

Note
Definition

fireEvent and userEvent are both utilities provided by React Testing Library to simulate user actions in tests. fireEvent triggers low-level DOM events directly, while userEvent simulates more realistic user interactions by firing a sequence of events as a real user would (for example, focusing an input before typing). userEvent is generally preferred for testing because it better reflects how users interact with your application.

question mark

Which statement best describes the difference between fireEvent and userEvent in React Testing Library?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 4

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

bookSimulating User Interactions

Pyyhkäise näyttääksesi valikon

When you are testing React components, it is essential to verify that user interactions trigger the expected behavior and state changes. React Testing Library provides utilities to simulate these interactions, allowing you to test how your components respond to user actions such as clicks, typing, or form submissions.

Suppose you have a simple button that updates a counter when clicked. To test this interaction, you can use either fireEvent or userEvent from React Testing Library. Here is an example of how you might write a test for a button click that updates component state:

Counter.jsx

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </div>
  );
}

Counter.test.jsx

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./Counter";

test("increments counter when button is clicked", async () => {
  const user = userEvent.setup();
  render(<Counter />);

  expect(screen.getByText("Count: 0")).toBeInTheDocument();

  await user.click(
    screen.getByRole("button", { name: /increment/i })
  );

  expect(screen.getByText("Count: 1")).toBeInTheDocument();
});

In this test, you render the Counter component, simulate a click on the increment button, and then assert that the displayed count has changed. This pattern helps ensure your UI behaves as expected in response to user events.

After simulating a user interaction, you should always assert that the DOM reflects the expected changes. This means checking for the presence or content of elements that should be updated as a result of the event. For instance, after clicking a button, you might expect a new message to appear, a value to increment, or a form field to clear. Using queries like getByText, queryByRole, or getByLabelText allows you to assert these changes and confirm your component is responding correctly to user input.

Note
Definition

fireEvent and userEvent are both utilities provided by React Testing Library to simulate user actions in tests. fireEvent triggers low-level DOM events directly, while userEvent simulates more realistic user interactions by firing a sequence of events as a real user would (for example, focusing an input before typing). userEvent is generally preferred for testing because it better reflects how users interact with your application.

question mark

Which statement best describes the difference between fireEvent and userEvent in React Testing Library?

Select the correct answer

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 4
some-alt