在 rtl 中,避免在单个测试中渲染多个组件?
In rtl, avoid rendering multiple components within a single test?
在 rtl 中,避免在单个测试中渲染多个组件?
例如,假设按下 header 中的按钮时侧边栏折叠。
为了测试这一点,我在一个测试中渲染了 header 和边栏,如下所示。
it("Fold/Unfold sidebar when click toggle button", async () => {
// Given
render(<Header />);
render(<Sidebar />);
const button = await screen.findByTestId("fold-sidebar-icon");
const sidebar = await screen.findByTestId("sidebar");
expect(sidebar).toHaveStyle({ width: styles.layout.sidebar.unfold });
// When: click fold button
fireEvent.click(button);
// Then: fold sidebar
expect(sidebar).toHaveStyle({ width: styles.layout.sidebar.fold });
// When: click unfold button
fireEvent.click(button);
// Then: unfold sidebar
expect(sidebar).toHaveStyle({ width: styles.layout.sidebar.unfold });
});
这是平时使用react测试库应该避免的动作吗?如果是这样,合适的测试结构是什么?
这似乎不是一个干净的解决方案。一个简单干净的解决方案是将您的组件包装成一个。例如
const TestApp = () => (
<div>
<Header />
<Sidebar />
</div>
);
这样,您的两个组件只显示和渲染一次:
render(<TestApp />);
否则,测试看起来没问题。
在 rtl 中,避免在单个测试中渲染多个组件?
例如,假设按下 header 中的按钮时侧边栏折叠。
为了测试这一点,我在一个测试中渲染了 header 和边栏,如下所示。
it("Fold/Unfold sidebar when click toggle button", async () => {
// Given
render(<Header />);
render(<Sidebar />);
const button = await screen.findByTestId("fold-sidebar-icon");
const sidebar = await screen.findByTestId("sidebar");
expect(sidebar).toHaveStyle({ width: styles.layout.sidebar.unfold });
// When: click fold button
fireEvent.click(button);
// Then: fold sidebar
expect(sidebar).toHaveStyle({ width: styles.layout.sidebar.fold });
// When: click unfold button
fireEvent.click(button);
// Then: unfold sidebar
expect(sidebar).toHaveStyle({ width: styles.layout.sidebar.unfold });
});
这是平时使用react测试库应该避免的动作吗?如果是这样,合适的测试结构是什么?
这似乎不是一个干净的解决方案。一个简单干净的解决方案是将您的组件包装成一个。例如
const TestApp = () => (
<div>
<Header />
<Sidebar />
</div>
);
这样,您的两个组件只显示和渲染一次:
render(<TestApp />);
否则,测试看起来没问题。