javascript - 如何在测试库/反应库中干涸查询
问题描述
我对虚拟计数器组件进行了以下简单测试:
describe("Counter", () => {
it("initially displays 0", () => {
render(<Counter />);
expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
});
it("displays the given initial value", () => {
render(<Counter initialValue={10} />);
expect(screen.getByText("Counter value is 10")).toBeInTheDocument();
});
it("has a button for incrementing the value", () => {
render(<Counter />);
userEvent.click(screen.getByRole("button", { name: "+1" }));
expect(screen.getByText("Counter value is 1")).toBeInTheDocument();
});
describe("when the maxValue is given", () => {
it("does not allow to increment the value above the given maximum", () => {
render(<Counter initialValue={9} maxValue={10} />);
userEvent.click(screen.getByRole("button", { name: "+1" }));
expect(screen.getByText("Counter value is 10")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "+1" })).toBeDisabled();
});
});
it("has a button for decrementing the value", () => {
render(<Counter initialValue={2} />);
userEvent.click(screen.getByRole("button", { name: "-1" }));
expect(screen.getByText("Counter value is 1")).toBeInTheDocument();
});
it("does not allow to decrement the value below zero", () => {
render(<Counter initialValue={0} />);
expect(screen.getByRole("button", { name: "-1" })).toBeDisabled();
userEvent.click(screen.getByRole("button", { name: "-1" }));
expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
});
it("has a button for resetting the value", () => {
render(<Counter initialValue={2} />);
userEvent.click(screen.getByRole("button", { name: "reset" }));
expect(screen.getByText("Counter value is 0")).toBeInTheDocument();
});
});
用一些方便的助手来干掉它是一个好习惯吗,比如:
describe("<Counter /> component", () => {
const getIncrementButton = () => screen.getByRole("button", { name: "+1" });
const getDecrementButton = () => screen.getByRole("button", { name: "-1" });
it("has a button for incrementing the value", () => {
render(<Counter />);
userEvent.click(getIncrementButton());
expect(getValue()).toHaveTextContent("Counter value is 1");
});
});
我做了一些研究,但找不到任何关于这种方法的体面资源。
解决方案
推荐阅读
- fpga - 将 DDR 控制器连接到叉骨
- android - 我们如何在 Android 11 的下载文件夹中写入 M3u 文件
- c++ - 如何使用递归打印 12 的表,我希望它达到 10,但在运行时结果达到 12
- python - Python Web-scraping youtube.com BeautifulSoup4 问题
- php - 如何在本地文件夹 laravel 中上传图片?
- r - 跨多列的 T 检验或整理数据
- javascript - 从 API 获取 json,在数组中的每个对象的 div 中创建 HTML 代码
- javascript - 如何在 PHP 和 python 中使用 HTML5 SSE
- perl - Perl 从文件中打印二维矩阵
- mysql - 保存用户交互并呈现它们