首页  >  文章  >  web前端  >  React 基础知识~单元测试/用户事件

React 基础知识~单元测试/用户事件

Linda Hamilton
Linda Hamilton原创
2024-10-21 12:47:30360浏览
  • 当我测试用户事件时,我使用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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn