Question:
Testing react component with jest

Problem:

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 the Context

  const { result } = renderHook(() => useToggleSidebar(), {

      wrapper: SidebarProvider

    });


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


Suggested blogs:

>How to destroy a custom object within the use Effect hook in TypeScript?

>Create a function that convert a dynamic Json to a formula in Typescript

>Narrow SomeType vs SomeType[]

>Why Typescript does not allow a union type in an array?

>Fix: Strange compilation error with Typescript and Angular

>What if the property 'X' does not exist on type 'FastifyContext<unknown>'?

>How to get the type of a class property's getter/setter in TypeScript?


Ritu Singh

Ritu Singh

Submit
0 Answers