首页 > 解决方案 > 如何在 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);
        ...
    });
});

有没有办法从第一个测试中保留相同的渲染以在第二个测试中使用,而不必重新渲染相同的组件并再次通过第一个问题来测试第二个问题?

标签: reactjsjestjsreact-testing-library

解决方案


基本上你需要的是禁用自动清理,因为它会在每次测试后卸载 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");
    });
});

推荐阅读