如何用jest测试react组件?

rdrgkggo  于 2023-11-15  发布在  Jest
关注(0)|答案(1)|浏览(190)

我想测试侧边栏组件。当你点击“ToggleButton”时,它应该按className切换侧边栏,但当点击时,出现一个错误,说明找不到该函数...
谢谢你,谢谢
错误:TypeError: setToggleSidebar is not a function

Sidebar.test.tsx

describe("Sidebar", () => {
  test("Toggle Sidebar", () => {
    const { result } = renderHook(() => useToggleSidebar());

    const { toggleSidebar } = result.current;

    ComponentRender(<ToggleButton toggleFunc={toggleSidebar} />);
    ComponentRender(<Sidebar />);

    fireEvent.click(screen.getByTestId("toggle-button"));

    expect(screen.getByTestId("sidebar")).toHaveClass("HiddenSidebar");
  });
});

字符串

componentRender.tsx

export function ComponentRender(component: JSX.Element, options: IComponentRenderOptions = {}) {
  const { route = "/dashboard", initialState } = options;

  return render(
    <ReduxProvider initialState={initialState}>
      <ThemeProvider>
        <SidebarProvider>
          <MemoryRouter initialEntries={[route]}>{component}</MemoryRouter>
        </SidebarProvider>
      </ThemeProvider>
    </ReduxProvider>,
  );
}

sidebarProvider.tsx

export const SidebarProvider = (props: PropsWithChildren) => {
  const { children } = props;

  const [isSidebarShow, setToggleSidebar] = useState<boolean>(false);

  const defaultValue: ISidebarDefault = useMemo(
    () => ({
      isSidebarShow,
      setToggleSidebar,
    }),
    [isSidebarShow],
  );

  return <SidebarContext.Provider value={defaultValue}>{children}</SidebarContext.Provider>;
};

useToggleSidebar.tsx

const useToggleSidebar = (): IUseToggleSidebar => {
  const { isSidebarShow, setToggleSidebar } = useContext(SidebarContext);

  const toggleSidebar = () => {
    setToggleSidebar((isSidebarShow: boolean) => !isSidebarShow);

    ^ <-- HERE IS ERROR setToggleSidebar is not a function

  };

  return { isSidebarShow, toggleSidebar };
};


我试图直接解构useToggleSidebar钩子

xe55xuns

xe55xuns1#

你必须把你的钩子 Package 在上下文中

const { result } = renderHook(() => useToggleSidebar(), {
      wrapper: SidebarProvider
    });

字符串
因为您在渲染useToggleSidebar时缺少上下文,所以只需要像模拟真实的useToggleSidebar一样模拟它

相关问题