【发布时间】:2020-07-09 19:46:39
【问题描述】:
在使用 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);
...
});
});
有没有办法保留第一个测试的相同渲染以用于第二个测试,而不是重新渲染相同的组件并再次遍历第一个问题以测试第二个问题?
【问题讨论】:
标签: reactjs jestjs react-testing-library