
当我测试一些当前代码时,我可以使用describe函数将代码分组。
在本例中,我创建了一个计数器应用程序。
・src/example.jsx
import counter from "./components/counter";
const example = () => {
const origincount = 0;
return ;
};
export default example;
・src/components/counter.jsx
import { usestate } from "react";
const counter = (props) => {
const { origincount } = props;
const [count, setcount] = usestate(origincount);
const countup = () => {
setcount(count + 1);
};
const countdown = () => {
setcount(count - 1);
};
const countclear = () => {
setcount(0);
};
return (
counter test
current count:{count}
);
};
export default counter;
・src/components/counter.test.jsx
import { fireEvent, render, screen } from "@testing-library/react";
import Counter from "./Counter";
//A group for initial test
describe("Counter", () => {
describe("Check the initial display", () => {
// ① A Confirming the Initial State
test("Whether
test("Whether the current count is 0 or not", () => {
render( );
const spanElBeforeUpdate = screen.getByText("Current count:0");
expect(spanElBeforeUpdate).toBeInTheDocument();
});
});
//A group for actions tests
describe("Control buttons", () => {
// ① count up
test("Whether the current count changes into 1 or not, in case the
countup button is clicked", () => {
render( );
const spanElBeforeUpdate = screen.getByText("Current count:0");
expect(spanElBeforeUpdate).toBeInTheDocument();
const btn = screen.getByRole("button", { name: "Countup" });
fireEvent.click(btn);
const spanEl = screen.getByText("Current count:1");
expect(spanEl).toBeInTheDocument();
});
// ② count down
test("Whether the current count changes into -1 or not, in case the
countdown button is clicked ", () => {
render( );
const spanElBeforeUpdate = screen.getByText("Current count:0");
expect(spanElBeforeUpdate).toBeInTheDocument();
const btn = screen.getByRole("button", { name: "Countdown" });
fireEvent.click(btn);
const spanEl = screen.getByText("Current count:-1");
expect(spanEl).toBeInTheDocument();
});
// ③ count clear
test("Whether the current count changes into 0 or not, in case the
clear button is clicked ", () => {
render( );
const spanElBeforeUpdate = screen.getByText("Current count:0");
expect(spanElBeforeUpdate).toBeInTheDocument();
const btn = screen.getByRole("button", { name: "Clear" });
fireEvent.click(btn);
const spanEl = screen.getByText("Current count:0");
expect(spanEl).toBeInTheDocument();
});
});
});
・计数
・倒计时
・倒计时
・成功
・失败










