reactjsreact-hooksjestjsreact-testing-libraryreact-test-renderer

How to test react component with jest?


I want to test the Sidebar component. When you click on the "ToggleButton" it should toggle sidebar by className, but when clicking, an error appears stating that the function was not found...

Thank you!

Error: 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 };
};

I tried to destructure the useToggleSidebar hook directly


Solution

  • You have to wrap your hook inside Context

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

    Beause you were rendering useToggleSidebar lack of context, just simulator it like the real one