Home > Web Front-end > JS Tutorial > body text

React Basics~unit test/user event

Linda Hamilton
Release: 2024-10-21 12:47:30
Original
350 people have browsed it
  • When I test a user event, I use the fireEvent function of the react-testing-library.

・src/Example.js

import Counter from "./components/Counter";

const Example = () => {
  const originCount = 0;

  return <Counter originCount={originCount}></Counter>;
};

export default Example;

Copy after login

・src/commponets/Counter.jsx

import { useState } from "react";

const Counter = (props) => {
  const { originCount } = props;
  const [count, setCount] = useState(originCount);

  const countUp = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h2>A test of counter</h2>
      <div>
        <span>Current count:{count}</span>
      </div>
      <div>
        <button onClick={countUp}>Countup</button>
      </div>
    </div>
  );
};

export default Counter;
Copy after login

・src/commponets/Counter.test.jsx

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

test("Whether the current count counts up or not, in case the countUp button is clicked ", () => {
  const { debug } = render(<Counter originCount={0} />);

//test the initial state.
  const spanElBeforUpdate = screen.getByText("Current count:0");
  expect(spanElBeforUpdate).toBeInTheDocument();

//test the user event. In this case, a click event.
  const btn = screen.getByRole("button", { name: "Countup" });
  fireEvent.click(btn);

//test the state which is after clicked button.
  const spanEl = screen.getByText("Current count:1");
  expect(spanEl).toBeInTheDocument();
});

Copy after login

・Success
React Basics~unit test/user event

・Failure
React Basics~unit test/user event

The above is the detailed content of React Basics~unit test/user event. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!