{ 戻る ; }; デフォルトの例をエクスポートします。 ・す"/> { 戻る ; }; デフォルトの例をエクスポートします。 ・す">

ホームページ  >  記事  >  ウェブフロントエンド  >  React の基本 ~単体テスト/UI

React の基本 ~単体テスト/UI

Linda Hamilton
Linda Hamiltonオリジナル
2024-10-20 16:41:02118ブラウズ
  • 現在のコードをテストするとき (単体テスト)、いくつかのツールを使用します。それらは jest と react-testing-library です。

・src/Example.js

import Greet from "./components/Greet";

const Example = () => {
  return <Greet />;
};

export default Example;

・src/component/Greet.jsx

const Greet = () => {
  return (
    <div>
      <form>
        <h1>Hello</h1>
        <input type="radio" />
        <label htmlFor="fullname">Fullname</label>
        <input id="fullname" type="text" placeholder="Fullname" />
        <button>button1</button>
        <button>button2</button>
        <img src="/logo512.png" alt="React Logo" />
        <h2>Hello2</h2>
      </form>
    </div>
  );
};

export default Greet;

・src/component/Greet.test.jsx

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

test("Whether elements exists or not", () => {
  const { debug, container } = render(<Greet />);
  //get the h1 element
  const h1El = screen.getByText("Hello");
  expect(h1El).toBeInTheDocument();

  //get the h2 element by specifying the name
  const headEl = screen.getByRole("heading", { name: "Hello2" });
  debug(headEl);
  expect(headEl).toBeInTheDocument();

  //get radio button
  const radioEl = screen.getByRole("radio");
  debug(radioEl);
  expect(radioEl).toBeInTheDocument();

  //get the img element
  const imgEl = screen.getByRole("img");
  debug(imgEl);
  expect(imgEl).toBeInTheDocument();

  //get the h1 element by getting the alt
  const imgEl2 = screen.getByAltText("React Logo");
  debug(imgEl2);
  expect(imgEl2).toBeInTheDocument();

  //get the h2 element by using the querySelector of container
  const h2El = container.querySelector("h2");
  debug(h2El);
  expect(h2El).toBeInTheDocument();

  //get an element by getting the labe
  const elByLabel = screen.getByLabelText("Fullname");
  debug(elByLabel);
  expect(elByLabel).toBeInTheDocument();

  //get an element by getting the placeholder
  const elByPlaceholder = screen.getByPlaceholderText("Fullname");
  debug(elByPlaceholder);
  expect(elByPlaceholder).toBeInTheDocument();
});


  • テスト関数はテストの関数です。

  • 最初の引数はテストのタイトルです。 2 番目の引数は、テスト コードを実行するコールバック関数です。

-コールバック関数では、レンダリング関数を使用してテストされるコンポーネントをレンダリングする必要があります。必要に応じてデバッグとコンテナを使用できます。

const { debug, container } = render(<Greet />);
  • 次に、screen.* を使用して要素を取得する必要があります。
    getByText()、getByRole()、getByAltText() などの関数がたくさんあります。

  • 最後に、expect(以前に取得した要素).toBeInTheDocument(); を使用して、要素がドキュメント内に存在するかどうかを知る必要があります。

  • テスト コードを作成した後、このコマンド npm test を実行する必要があります。

・成功(テストに合格)

React Basics~unit test/ui

・失敗(テストは失敗しました)

React Basics~unit test/ui

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

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。