・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 基础知识~单元测试/用户事件的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号