我想测试侧边栏组件。当你点击“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钩子
1条答案
按热度按时间xe55xuns1#
你必须把你的钩子 Package 在上下文中
字符串
因为您在渲染
useToggleSidebar
时缺少上下文,所以只需要像模拟真实的useToggleSidebar
一样模拟它