reactjs - 如何在 React 测试库中的多个测试中使用单个渲染。?
问题描述
在使用 Jest 和 React 测试库时,是否可以在多个测试中保持相同的 render()?我正在构建一个 Trivia 应用程序,并且有一个组件可以在用户完成测验时显示不同的问题。为了测试选择按钮、提交按钮的功能,并检查正确的屏幕是否在正确的时间显示,我需要在测验的不同阶段对相同的渲染组件执行测试。例如:
describe("Question Screen", () => {
it("should render the first question when difficulty button is clicked", async () => {
render(<TriviaBox/>);
const btn = screen.getByRole("button", {name: /easy/i});
fireEvent.click(btn);
const heading = await screen.findByText("Question 1");
expect(heading).toBeInTheDocument();
});
it("should display the next question when the current question is answered", async () => {
render(<TriviaBox/>);
const btn = screen.getByRole("button", {name: /easy/i});
fireEvent.click(btn);
const correctAnswer = await screen.findByRole("button", {name: /Nevada/i});
const submit = await screen.findByRole("button", {name: /Submit/i});
fireEvent.click(correctAnswer);
fireEvent.click(submit);
expect(wait screen.findByText("Question 2")).toBeInTheDocument();
expect(wait screen.findByText("Which is the largest state?")).toBeInTheDocument();
expect(wait screen.findAllByRole("radio")).toHaveLength(4);
...
});
});
有没有办法从第一个测试中保留相同的渲染以在第二个测试中使用,而不必重新渲染相同的组件并再次通过第一个问题来测试第二个问题?
解决方案
基本上你需要的是禁用自动清理,因为它会在每次测试后卸载 React 树。请参阅文档:https ://testing-library.com/docs/react-testing-library/setup/#skipping-auto-cleanup 。但在这种情况下,您应该关心手动调用 cleanup 以免影响下一个测试。
这是一个小的工作示例,说明如何通过导入“@testing-library/react/dont-cleanup-after-each”来做到这一点:
import "@testing-library/react/dont-cleanup-after-each";
import { render, screen, cleanup } from "@testing-library/react";
function TestComponent() {
return (
<div>
<p>First element</p>
<p>Second element</p>
</div>
);
}
describe("TestComponent", () => {
afterAll(() => {
cleanup();
});
it("should contain `First element` text", () => {
render(<TestComponent />);
screen.getByText("First element");
});
it("should contain `Second element` text", () => {
screen.getByText("Second element");
});
});
推荐阅读
- java - 如何编写一个类来对指定单元位置周围的矩阵单元求和?
- c#-3.0 - Discord.net 是否可以以编程方式添加自定义服务器表情符号反应?
- java - 为什么在 Java 中调用 curl 没有传递正确的参数?
- sql - 查询 START_DATE 比 END_DATE 大 1 天
- python - 如何在python中获取子数组?
- javascript - 正则表达式还捕获除捕获组之外的所有内容
- java - 如何在 Java 中导航一组图像文件对象?
- python - MySQL db 无法在 Python 2.7 Raspberry Pi3 上运行
- excel - 如何在 Excel 上使用 getElementbyID 从网站中提取数据
- typescript - TypeScript 条件返回错误