首頁 > web前端 > js教程 > 主體

React 基礎知識~單元測驗/ui

Linda Hamilton
發布: 2024-10-20 16:41:02
原創
116 人瀏覽過
  • 當我測試目前程式碼(即單元測試)時,我使用了一些工具。它們是笑話和反應測試庫。

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


登入後複製
  • 測試函數是測試的函數。

  • 第一個參數是測試標題。第二個參數是執行測試程式碼的回呼函數。

-在回調函數中,我需要渲染一個將使用渲染函數進行測試的元件。如果需要的話我可以使用調試和容器。

const { debug, container } = render(<Greet />);
登入後複製
  • 然後,我需要使用 screen.* 取得一個元素。
    有許多函數,例如 getByText()、getByRole()、getByAltText() 等。

  • 最後,我需要知道文件中是否存在該元素,使用expect(我之前得到的element).toBeInTheDocument();.

  • 寫測試程式碼後,我需要執行這個指令 npm test。

・成功(測驗通過)

React Basics~unit test/ui

・失敗(測試失敗)

React Basics~unit test/ui

以上是React 基礎知識~單元測驗/ui的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!