React の基本 ~単体テスト/ユーザー イベント

Linda Hamilton
リリース: 2024-10-21 12:47:30
オリジナル
350 人が閲覧しました
  • ユーザー イベントをテストするときは、react-testing-library の fireEvent 関数を使用します。

・src/Example.js

import Counter from "./components/Counter";

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

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

export default Example;

ログイン後にコピー

・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;
ログイン後にコピー

・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();
});

ログイン後にコピー

・成功
React Basics~unit test/user event

・失敗
React Basics~unit test/user event

以上がReact の基本 ~単体テスト/ユーザー イベントの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!