[英]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 });
});
這是在通常使用反應測試庫時應該避免的行為嗎? 如果是這樣,合適的測試結構是什么?
這似乎不是一個干凈的解決方案。 一個簡單的清潔解決方案是將您的組件包裝成一個。 例如
const TestApp = () => (
<div>
<Header />
<Sidebar />
</div>
);
這樣,您的兩個組件都只顯示和渲染一次:
render(<TestApp />);
否則,測試看起來沒問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.