- 当我测试用户事件时,我使用react-testing-library的fireevent函数。
・src/example.js
import counter from "./components/counter";
const example = () => {
const origincount = 0;
return ;
};
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 (
a test of counter
current count:{count}
);
};
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( );
//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();
});
・成功
・失败










