cro*_*lat 5 reactjs jestjs react-testing-library
使用 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);
...
});
});
Run Code Online (Sandbox Code Playgroud)
有没有办法保留第一个测试中的相同渲染以在第二个测试中使用,而不是必须重新渲染相同的组件并再次单步执行第一个问题才能测试第二个问题?
Yar*_*bay 11
基本上你需要的是禁用自动清理,因为它会在每次测试后卸载 React 树。请参阅文档:https://testing-library.com/docs/react-testing-library/setup/#skipping-auto-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");
});
});
Run Code Online (Sandbox Code Playgroud)
一种方法是编写一个beforeAll函数来初始化渲染。对于所有子测试,这只会初始化一次。
describe("Question Screen", () => {
beforeAll(() => {
render(<TriviaBox/>);
})
it("should render the first question when difficulty button is clicked", async () => {
const btn = screen.getByRole("button", {name: /easy/i});
fireEvent.click(btn);
const heading = await screen.findByText("Question 1");
expect(heading).toBeInTheDocument();
});
...
});
Run Code Online (Sandbox Code Playgroud)
请参阅 JEST 文档https://jestjs.io/docs/en/setup-teardown#one-time-setup
| 归档时间: |
|
| 查看次数: |
9872 次 |
| 最近记录: |