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

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中文網其他相關文章!

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