1 import React from "react"
2 import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"
3 import { cleanup, fireEvent, render, waitFor } from "@testing-library/react"
4 import type { Sidebar } from "types"
5
6 // Mock dependencies
7 const mockUseSiteConfig = vi.fn(() => ({
8 config: {
9 project: {
10 title: "Test Project",
11 key: "test-project",
12 },
13 },
14 }))
15
16 const mockUseIsBrowser = vi.fn(() => ({
17 isBrowser: true,
18 }))
19
20 const mockUsePathname = vi.fn(() => "/test-path")
21
22 const mockPush = vi.fn()
23 const mockReplace = vi.fn()
24 const mockUseRouter = vi.fn(() => ({
25 push: mockPush,
26 replace: mockReplace,
27 }))
28
29 const mockGetScrolledTop = vi.fn(() => 0)
30
31 vi.mock("@/providers/SiteConfig", () => ({
32 useSiteConfig: () => mockUseSiteConfig(),
33 }))
34
35 vi.mock("@/providers/BrowserProvider", () => ({
36 useIsBrowser: () => mockUseIsBrowser(),
37 }))
38
39 vi.mock("next/navigation", () => ({
40 usePathname: () => mockUsePathname(),
41 useRouter: () => mockUseRouter(),
42 }))
43
44 vi.mock("@/utils/get-scrolled-top", () => ({
45 getScrolledTop: () => mockGetScrolledTop(),
46 }))
47
48 // Test data
49 const mockSidebar1: Sidebar.Sidebar = {
50 sidebar_id: "sidebar-1",
51 title: "Sidebar 1",
52 items: [
53 {
54 type: "link",
55 path: "/test-path",
56 title: "Test Link",
57 },
58 {
59 type: "category",
60 title: "Category 1",
61 children: [
62 {
63 type: "link",
64 path: "/category-1/item-1",
65 title: "Item 1",
66 },
67 {
68 type: "link",
69 path: "/category-1/item-2",
70 title: "Item 2",
71 },
72 ],
73 },
74 {
75 type: "link",
76 path: "/item-3",
77 title: "Item 3",
78 children: [
79 {
80 type: "link",
81 path: "/item-3/item-3-1",
82 title: "Item 3-1",
83 },
84 ],
85 },
86 ],
87 }
88
89 const mockSidebar2: Sidebar.Sidebar = {
90 sidebar_id: "sidebar-2",
91 title: "Sidebar 2",
92 items: [
93 {
94 type: "link",
95 path: "/sidebar-2/item-1",
96 title: "Sidebar 2 Item 1",
97 },
98 ],
99 }
100
101 const mockSidebar3: Sidebar.Sidebar = {
102 sidebar_id: "sidebar-3",
103 title: "Sidebar 3",
104 items: [
105 {
106 type: "link",
107 path: "#hash-path",
108 title: "Hash Path",
109 },
110 ],
111 }
112
113 import { SidebarProvider, useSidebar } from "../index"
114
115 const TestComponent = () => {
116 const sidebar = useSidebar()
117 if (!sidebar) {
118 return null
119 }
120
121 return (
122 <div>
123 <div data-testid="sidebars-count">{sidebar.sidebars.length}</div>
124 <div data-testid="active-path">{sidebar.activePath || "none"}</div>
125 <div data-testid="active-item-title">
126 {sidebar.activeItem?.title || "none"}
127 </div>
128 <div data-testid="shown-sidebar-id">
129 {sidebar.shownSidebar?.sidebar_id || "none"}
130 </div>
131 <div data-testid="mobile-open">
132 {sidebar.mobileSidebarOpen ? "open" : "closed"}
133 </div>
134 <div data-testid="desktop-open">
135 {sidebar.desktopSidebarOpen ? "open" : "closed"}
136 </div>
137 <div data-testid="sidebar-history">
138 {sidebar.sidebarHistory.join(",") || "none"}
139 </div>
140 <div data-testid="sidebar-top-height">{sidebar.sidebarTopHeight}</div>
141 <button
142 data-testid="set-active-path"
143 onClick={() => sidebar.setActivePath("/test-path")}
144 >
145 Set Active Path
146 </button>
147 <button
148 data-testid="set-mobile-open"
149 onClick={() => sidebar.setMobileSidebarOpen(true)}
150 >
151 Open Mobile
152 </button>
153 <button
154 data-testid="set-desktop-open"
155 onClick={() => sidebar.setDesktopSidebarOpen(false)}
156 >
157 Close Desktop
158 </button>
159 <button
160 data-testid="set-sidebar-top-height"
161 onClick={() => sidebar.setSidebarTopHeight(100)}
162 >
163 Set Height
164 </button>
165 <button
166 data-testid="add-items"
167 onClick={() =>
168 sidebar.addItems(
169 [
170 {
171 type: "link",
172 path: "/new-item",
173 title: "New Item",
174 },
175 ],
176 { sidebar_id: "sidebar-1" }
177 )
178 }
179 >
180 Add Items
181 </button>
182 <button
183 data-testid="update-items"
184 onClick={() =>
185 sidebar.updateItems({
186 sidebar_id: "sidebar-1",
187 items: [
188 {
189 existingItem: mockSidebar1.items[0] as Sidebar.SidebarItem,
190 newItem: { title: "Updated Title" },
191 },
192 ],
193 })
194 }
195 >
196 Update Items
197 </button>
198 <button
199 data-testid="remove-items"
200 onClick={() =>
201 sidebar.removeItems({
202 items: [mockSidebar1.items[0] as Sidebar.SidebarItem],
203 sidebar_id: "sidebar-1",
204 })
205 }
206 >
207 Remove Items
208 </button>
209 <button data-testid="reset-items" onClick={() => sidebar.resetItems()}>
210 Reset Items
211 </button>
212 <button data-testid="go-back" onClick={() => sidebar.goBack()}>
213 Go Back
214 </button>
215 <button
216 data-testid="update-category-state"
217 onClick={() => sidebar.updatePersistedCategoryState("Category 1", true)}
218 >
219 Update Category State
220 </button>
221 <div data-testid="category-state">
222 {sidebar.getPersistedCategoryState("Category 1")?.toString() || "none"}
223 </div>
224 <div data-testid="is-item-active">
225 {sidebar.isItemActive({
226 item: mockSidebar1.items[0] as Sidebar.InteractiveSidebarItem,
227 })
228 ? "active"
229 : "inactive"}
230 </div>
231 </div>
232 )
233 }
234
235 beforeEach(() => {
236 vi.clearAllMocks()
237 localStorage.clear()
238 mockUseSiteConfig.mockReturnValue({
239 config: {
240 project: {
241 title: "Test Project",
242 key: "test-project",
243 },
244 },
245 })
246 mockUseIsBrowser.mockReturnValue({
247 isBrowser: true,
248 })
249 mockUsePathname.mockReturnValue("/test-path")
250 mockGetScrolledTop.mockReturnValue(0)
251 mockPush.mockClear()
252 mockReplace.mockClear()
253
254 // Mock window.location.hash
255 Object.defineProperty(window, "location", {
256 value: {
257 hash: "",
258 },
259 writable: true,
260 configurable: true,
261 })
262
263 // Mock document.getElementsByTagName
264 Object.defineProperty(document, "getElementsByTagName", {
265 value: vi.fn(() => [{ length: 1 }] as unknown as HTMLCollectionOf<Element>),
266 writable: true,
267 configurable: true,
268 })
269 })
270
271 afterEach(() => {
272 cleanup()
273 localStorage.clear()
274 })
275
276 describe("rendering", () => {
277 test("renders children", () => {
278 const { container } = render(
279 <SidebarProvider sidebars={[mockSidebar1]}>
280 <div>Test</div>
281 </SidebarProvider>
282 )
283 expect(container).toHaveTextContent("Test")
284 })
285 })
286
287 describe("useSidebar hook", () => {
288 test("initializes with provided sidebars", () => {
289 const { getByTestId } = render(
290 <SidebarProvider sidebars={[mockSidebar1, mockSidebar2]}>
291 <TestComponent />
292 </SidebarProvider>
293 )
294
295 expect(getByTestId("sidebars-count")).toHaveTextContent("2")
296 })
297
298 test("sets active path from pathname", async () => {
299 mockUsePathname.mockReturnValue("/test-path")
300 const { getByTestId } = render(
301 <SidebarProvider sidebars={[mockSidebar1]} shouldHandlePathChange={true}>
302 <TestComponent />
303 </SidebarProvider>
304 )
305
306 await waitFor(() => {
307 expect(getByTestId("active-path")).toHaveTextContent("/test-path")
308 })
309 })
310
311 test("finds active item from active path", async () => {
312 mockUsePathname.mockReturnValue("/test-path")
313 const { getByTestId } = render(
314 <SidebarProvider sidebars={[mockSidebar1]} shouldHandlePathChange={true}>
315 <TestComponent />
316 </SidebarProvider>
317 )
318
319 await waitFor(() => {
320 expect(getByTestId("active-item-title")).toHaveTextContent("Test Link")
321 })
322 })
323
324 test("sets shown sidebar to first sidebar when single sidebar", () => {
325 const { getByTestId } = render(
326 <SidebarProvider sidebars={[mockSidebar1]}>
327 <TestComponent />
328 </SidebarProvider>
329 )
330
331 expect(getByTestId("shown-sidebar-id")).toHaveTextContent("sidebar-1")
332 })
333
334 test("mobileSidebarOpen defaults to false", () => {
335 const { getByTestId } = render(
336 <SidebarProvider sidebars={[mockSidebar1]}>
337 <TestComponent />
338 </SidebarProvider>
339 )
340
341 expect(getByTestId("mobile-open")).toHaveTextContent("closed")
342 })
343
344 test("desktopSidebarOpen defaults to true", () => {
345 const { getByTestId } = render(
346 <SidebarProvider sidebars={[mockSidebar1]}>
347 <TestComponent />
348 </SidebarProvider>
349 )
350
351 expect(getByTestId("desktop-open")).toHaveTextContent("open")
352 })
353
354 test("loads desktop sidebar state from localStorage", async () => {
355 localStorage.setItem("hide_sidebar", "true")
356 const { getByTestId } = render(
357 <SidebarProvider sidebars={[mockSidebar1]}>
358 <TestComponent />
359 </SidebarProvider>
360 )
361
362 await waitFor(() => {
363 expect(getByTestId("desktop-open")).toHaveTextContent("closed")
364 })
365 })
366
367 test("setActivePath updates active path", async () => {
368 const { getByTestId } = render(
369 <SidebarProvider sidebars={[mockSidebar1]}>
370 <TestComponent />
371 </SidebarProvider>
372 )
373
374 fireEvent.click(getByTestId("set-active-path"))
375
376 await waitFor(() => {
377 expect(getByTestId("active-path")).toHaveTextContent("/test-path")
378 })
379 })
380
381 test("setMobileSidebarOpen updates mobile sidebar state", () => {
382 const { getByTestId } = render(
383 <SidebarProvider sidebars={[mockSidebar1]}>
384 <TestComponent />
385 </SidebarProvider>
386 )
387
388 fireEvent.click(getByTestId("set-mobile-open"))
389
390 expect(getByTestId("mobile-open")).toHaveTextContent("open")
391 })
392
393 test("setDesktopSidebarOpen updates desktop sidebar state and localStorage", async () => {
394 const { getByTestId } = render(
395 <SidebarProvider sidebars={[mockSidebar1]}>
396 <TestComponent />
397 </SidebarProvider>
398 )
399
400 fireEvent.click(getByTestId("set-desktop-open"))
401
402 await waitFor(() => {
403 expect(getByTestId("desktop-open")).toHaveTextContent("closed")
404 expect(localStorage.getItem("hide_sidebar")).toBe("true")
405 })
406 })
407
408 test("setSidebarTopHeight updates sidebar top height", () => {
409 const { getByTestId } = render(
410 <SidebarProvider sidebars={[mockSidebar1]}>
411 <TestComponent />
412 </SidebarProvider>
413 )
414
415 fireEvent.click(getByTestId("set-sidebar-top-height"))
416
417 expect(getByTestId("sidebar-top-height")).toHaveTextContent("100")
418 })
419
420 test("addItems adds items to sidebar", async () => {
421 const TestComponentWithItems = () => {
422 const sidebar = useSidebar()
423 return (
424 <div>
425 <div data-testid="items-count">
426 {sidebar.sidebars[0]?.items.length || 0}
427 </div>
428 <button
429 data-testid="add-items"
430 onClick={() =>
431 sidebar.addItems(
432 [
433 {
434 type: "link",
435 path: "/new-item",
436 title: "New Item",
437 },
438 ],
439 { sidebar_id: "sidebar-1" }
440 )
441 }
442 >
443 Add Items
444 </button>
445 </div>
446 )
447 }
448
449 const { getByTestId } = render(
450 <SidebarProvider sidebars={[mockSidebar1]}>
451 <TestComponentWithItems />
452 </SidebarProvider>
453 )
454
455 const initialCount = mockSidebar1.items.length
456 expect(getByTestId("items-count")).toHaveTextContent(
457 initialCount.toString()
458 )
459
460 fireEvent.click(getByTestId("add-items"))
461
462 await waitFor(() => {
463 expect(Number(getByTestId("items-count").textContent)).toBeGreaterThan(
464 initialCount
465 )
466 })
467 })
468
469 test("updateItems updates existing items", async () => {
470 const TestComponentWithUpdate = () => {
471 const sidebar = useSidebar()
472 const updatedItem = sidebar.sidebars[0]?.items.find(
473 (item) => item.type === "link" && item.path === "/test-path"
474 )
475 return (
476 <div>
477 <div data-testid="updated-title">
478 {updatedItem && updatedItem.type === "link"
479 ? updatedItem.title
480 : "not found"}
481 </div>
482 <button
483 data-testid="update-items"
484 onClick={() =>
485 sidebar.updateItems({
486 sidebar_id: "sidebar-1",
487 items: [
488 {
489 existingItem: mockSidebar1.items[0] as Sidebar.SidebarItem,
490 newItem: { title: "Updated Title" },
491 },
492 ],
493 })
494 }
495 >
496 Update Items
497 </button>
498 </div>
499 )
500 }
501
502 const { getByTestId } = render(
503 <SidebarProvider sidebars={[mockSidebar1]}>
504 <TestComponentWithUpdate />
505 </SidebarProvider>
506 )
507
508 expect(getByTestId("updated-title")).toHaveTextContent("Test Link")
509
510 fireEvent.click(getByTestId("update-items"))
511
512 await waitFor(() => {
513 expect(getByTestId("updated-title")).toHaveTextContent("Updated Title")
514 })
515 })
516
517 test("removeItems removes items from sidebar", async () => {
518 const TestComponentWithRemove = () => {
519 const sidebar = useSidebar()
520 return (
521 <div>
522 <div data-testid="items-count">
523 {sidebar.sidebars[0]?.items.length || 0}
524 </div>
525 <button
526 data-testid="remove-items"
527 onClick={() =>
528 sidebar.removeItems({
529 items: [mockSidebar1.items[0] as Sidebar.SidebarItem],
530 sidebar_id: "sidebar-1",
531 })
532 }
533 >
534 Remove Items
535 </button>
536 </div>
537 )
538 }
539
540 const { getByTestId } = render(
541 <SidebarProvider sidebars={[mockSidebar1]}>
542 <TestComponentWithRemove />
543 </SidebarProvider>
544 )
545
546 const initialCount = mockSidebar1.items.length
547 expect(getByTestId("items-count")).toHaveTextContent(
548 initialCount.toString()
549 )
550
551 fireEvent.click(getByTestId("remove-items"))
552
553 await waitFor(() => {
554 expect(Number(getByTestId("items-count").textContent)).toBeLessThan(
555 initialCount
556 )
557 })
558 })
559
560 test("resetItems resets sidebar to initial state", async () => {
561 const TestComponentWithReset = () => {
562 const sidebar = useSidebar()
563 return (
564 <div>
565 <div data-testid="items-count">
566 {sidebar.sidebars[0]?.items.length || 0}
567 </div>
568 <button
569 data-testid="add-items"
570 onClick={() =>
571 sidebar.addItems(
572 [
573 {
574 type: "link",
575 path: "/new-item",
576 title: "New Item",
577 },
578 ],
579 { sidebar_id: "sidebar-1" }
580 )
581 }
582 >
583 Add Items
584 </button>
585 <button
586 data-testid="reset-items"
587 onClick={() => sidebar.resetItems()}
588 >
589 Reset Items
590 </button>
591 </div>
592 )
593 }
594
595 const { getByTestId } = render(
596 <SidebarProvider sidebars={[mockSidebar1]}>
597 <TestComponentWithReset />
598 </SidebarProvider>
599 )
600
601 const initialCount = mockSidebar1.items.length
602 expect(getByTestId("items-count")).toHaveTextContent(
603 initialCount.toString()
604 )
605
606 // Add an item first
607 fireEvent.click(getByTestId("add-items"))
608
609 await waitFor(() => {
610 expect(Number(getByTestId("items-count").textContent)).toBeGreaterThan(
611 initialCount
612 )
613 })
614
615 // Then reset
616 fireEvent.click(getByTestId("reset-items"))
617
618 await waitFor(() => {
619 expect(getByTestId("items-count")).toHaveTextContent(
620 initialCount.toString()
621 )
622 })
623 })
624
625 test("isItemActive returns true for active item", async () => {
626 mockUsePathname.mockReturnValue("/test-path")
627 const { getByTestId } = render(
628 <SidebarProvider sidebars={[mockSidebar1]} shouldHandlePathChange={true}>
629 <TestComponent />
630 </SidebarProvider>
631 )
632
633 await waitFor(() => {
634 expect(getByTestId("is-item-active")).toHaveTextContent("active")
635 })
636 })
637
638 test("isItemActive returns false for inactive item", async () => {
639 mockUsePathname.mockReturnValue("/other-path")
640 const { getByTestId } = render(
641 <SidebarProvider sidebars={[mockSidebar1]} shouldHandlePathChange={true}>
642 <TestComponent />
643 </SidebarProvider>
644 )
645
646 await waitFor(() => {
647 expect(getByTestId("is-item-active")).toHaveTextContent("inactive")
648 })
649 })
650
651 test("isItemActive checks children when checkLinkChildren is true", async () => {
652 mockUsePathname.mockReturnValue("/category-1/item-1")
653 const TestComponentWithChild = () => {
654 const sidebar = useSidebar()
655 return (
656 <div>
657 <div data-testid="category-active">
658 {sidebar.isItemActive({
659 item: mockSidebar1.items[1] as Sidebar.InteractiveSidebarItem,
660 checkLinkChildren: true,
661 })
662 ? "active"
663 : "inactive"}
664 </div>
665 </div>
666 )
667 }
668
669 const { getByTestId } = render(
670 <SidebarProvider sidebars={[mockSidebar1]} shouldHandlePathChange={true}>
671 <TestComponentWithChild />
672 </SidebarProvider>
673 )
674
675 await waitFor(() => {
676 expect(getByTestId("category-active")).toHaveTextContent("active")
677 })
678 })
679
680 test("isItemActive does not check link children when checkLinkChildren is false", async () => {
681 mockUsePathname.mockReturnValue("/item-3/item-3-1")
682 const TestComponentWithChild = () => {
683 const sidebar = useSidebar()
684 return (
685 <div>
686 <div data-testid="link-inactive">
687 {sidebar.isItemActive({
688 item: mockSidebar1.items[2] as Sidebar.InteractiveSidebarItem,
689 checkLinkChildren: false,
690 })
691 ? "active"
692 : "inactive"}
693 </div>
694 </div>
695 )
696 }
697
698 const { getByTestId } = render(
699 <SidebarProvider sidebars={[mockSidebar1]} shouldHandlePathChange={true}>
700 <TestComponentWithChild />
701 </SidebarProvider>
702 )
703
704 await waitFor(() => {
705 expect(getByTestId("link-inactive")).toHaveTextContent("inactive")
706 })
707 })
708
709 test("isItemActive checks category children when checkLinkChildren is false", async () => {
710 mockUsePathname.mockReturnValue("/category-1/item-1")
711 const TestComponentWithChild = () => {
712 const sidebar = useSidebar()
713 return (
714 <div>
715 <div data-testid="category-active">
716 {sidebar.isItemActive({
717 item: mockSidebar1.items[1] as Sidebar.InteractiveSidebarItem,
718 checkLinkChildren: false,
719 })
720 ? "active"
721 : "inactive"}
722 </div>
723 </div>
724 )
725 }
726
727 const { getByTestId } = render(
728 <SidebarProvider sidebars={[mockSidebar1]} shouldHandlePathChange={true}>
729 <TestComponentWithChild />
730 </SidebarProvider>
731 )
732
733 await waitFor(() => {
734 expect(getByTestId("category-active")).toHaveTextContent("active")
735 })
736 })
737
738 test("getSidebar returns sidebar by id", () => {
739 const TestComponentWithGetSidebar = () => {
740 const sidebar = useSidebar()
741 const foundSidebar = sidebar.getSidebar("sidebar-1")
742 return (
743 <div data-testid="found-sidebar-id">
744 {foundSidebar?.sidebar_id || "none"}
745 </div>
746 )
747 }
748
749 const { getByTestId } = render(
750 <SidebarProvider sidebars={[mockSidebar1, mockSidebar2]}>
751 <TestComponentWithGetSidebar />
752 </SidebarProvider>
753 )
754
755 expect(getByTestId("found-sidebar-id")).toHaveTextContent("sidebar-1")
756 })
757
758 test("getSidebarFirstLinkChild returns first link child", () => {
759 const TestComponentWithGetFirstLink = () => {
760 const sidebar = useSidebar()
761 const firstLink = sidebar.getSidebarFirstLinkChild(mockSidebar1)
762 return (
763 <div data-testid="first-link-path">{firstLink?.path || "none"}</div>
764 )
765 }
766
767 const { getByTestId } = render(
768 <SidebarProvider sidebars={[mockSidebar1]}>
769 <TestComponentWithGetFirstLink />
770 </SidebarProvider>
771 )
772
773 expect(getByTestId("first-link-path")).toHaveTextContent("/test-path")
774 })
775
776 test("goBack navigates to previous sidebar in history", async () => {
777 const sidebarWithNested: Sidebar.Sidebar = {
778 sidebar_id: "main",
779 title: "Main Sidebar",
780 items: [
781 {
782 type: "sidebar",
783 sidebar_id: "nested",
784 title: "Nested Sidebar",
785 children: [
786 {
787 type: "link",
788 path: "/nested/item",
789 title: "Nested Item",
790 },
791 ],
792 },
793 ],
794 }
795
796 const nestedSidebar: Sidebar.Sidebar = {
797 sidebar_id: "nested",
798 title: "Nested Sidebar",
799 items: [
800 {
801 type: "link",
802 path: "/nested/item",
803 title: "Nested Item",
804 },
805 ],
806 }
807
808 mockUsePathname.mockReturnValue("/nested/item")
809 const { getByTestId } = render(
810 <SidebarProvider
811 sidebars={[sidebarWithNested, nestedSidebar]}
812 shouldHandlePathChange={true}
813 >
814 <TestComponent />
815 </SidebarProvider>
816 )
817
818 await waitFor(() => {
819 expect(getByTestId("sidebar-history")).not.toHaveTextContent("none")
820 })
821
822 fireEvent.click(getByTestId("go-back"))
823
824 await waitFor(() => {
825 expect(mockReplace).toHaveBeenCalled()
826 })
827 })
828
829 test("updatePersistedCategoryState saves to localStorage", async () => {
830 const { getByTestId } = render(
831 <SidebarProvider sidebars={[mockSidebar1]} persistCategoryState={true}>
832 <TestComponent />
833 </SidebarProvider>
834 )
835
836 fireEvent.click(getByTestId("update-category-state"))
837
838 await waitFor(() => {
839 const storageData = JSON.parse(
840 localStorage.getItem("Test Project_categories") || "{}"
841 )
842 expect(storageData["Test Project"]["Category 1"]).toBe(true)
843 })
844 })
845
846 test("getPersistedCategoryState retrieves from localStorage", async () => {
847 localStorage.setItem(
848 "Test Project_categories",
849 JSON.stringify({
850 "Test Project": {
851 "Category 1": true,
852 },
853 })
854 )
855
856 const { getByTestId } = render(
857 <SidebarProvider sidebars={[mockSidebar1]} persistCategoryState={true}>
858 <TestComponent />
859 </SidebarProvider>
860 )
861
862 await waitFor(() => {
863 expect(getByTestId("category-state")).toHaveTextContent("true")
864 })
865 })
866
867 test("getPersistedCategoryState returns undefined for non-existent category", () => {
868 const { getByTestId } = render(
869 <SidebarProvider sidebars={[mockSidebar1]} persistCategoryState={true}>
870 <TestComponent />
871 </SidebarProvider>
872 )
873
874 expect(getByTestId("category-state")).toHaveTextContent("none")
875 })
876
877 test("handles hash change when shouldHandleHashChange is true and shouldHandlePathChange is false", async () => {
878 Object.defineProperty(window, "location", {
879 value: {
880 hash: "#hash-path",
881 },
882 writable: true,
883 configurable: true,
884 })
885
886 const { getByTestId } = render(
887 <SidebarProvider
888 sidebars={[mockSidebar3]}
889 shouldHandleHashChange={true}
890 shouldHandlePathChange={false}
891 >
892 <TestComponent />
893 </SidebarProvider>
894 )
895
896 await waitFor(() => {
897 // init() removes the # from the hash
898 expect(getByTestId("active-path")).toHaveTextContent("hash-path")
899 })
900 })
901
902 test("does not handle hash change when shouldHandleHashChange is false", async () => {
903 Object.defineProperty(window, "location", {
904 value: {
905 hash: "#/hash-path",
906 },
907 writable: true,
908 configurable: true,
909 })
910
911 mockUsePathname.mockReturnValue("/test-path")
912 const { getByTestId } = render(
913 <SidebarProvider
914 sidebars={[mockSidebar1]}
915 shouldHandleHashChange={false}
916 shouldHandlePathChange={true}
917 >
918 <TestComponent />
919 </SidebarProvider>
920 )
921
922 await waitFor(() => {
923 expect(getByTestId("active-path")).toHaveTextContent("/test-path")
924 })
925 })
926
927 test("handles scroll when shouldHandleHashChange is true", async () => {
928 mockGetScrolledTop.mockReturnValue(30) // Between 0 and 56
929
930 const TestComponentWithScroll = () => {
931 const sidebar = useSidebar()
932 return (
933 <div>
934 <div data-testid="scroll-active-path">
935 {sidebar.activePath || "none"}
936 </div>
937 </div>
938 )
939 }
940
941 const scrollableElement = document.createElement("div")
942 render(
943 <SidebarProvider
944 sidebars={[mockSidebar1]}
945 shouldHandleHashChange={true}
946 scrollableElement={scrollableElement}
947 >
948 <TestComponentWithScroll />
949 </SidebarProvider>
950 )
951
952 // Simulate scroll event
953 fireEvent.scroll(scrollableElement)
954
955 await waitFor(() => {
956 expect(mockGetScrolledTop).toHaveBeenCalled()
957 })
958 })
959
960 test("calls setIsLoading when sidebars are loaded", async () => {
961 const setIsLoading = vi.fn()
962 render(
963 <SidebarProvider
964 sidebars={[mockSidebar1]}
965 isLoading={true}
966 setIsLoading={setIsLoading}
967 >
968 <div>Test</div>
969 </SidebarProvider>
970 )
971
972 await waitFor(() => {
973 expect(setIsLoading).toHaveBeenCalledWith(false)
974 })
975 })
976
977 test("throws error when used outside provider", () => {
978 const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {})
979
980 expect(() => {
981 render(<TestComponent />)
982 }).toThrow("useSidebar must be used inside a SidebarProvider")
983
984 consoleSpy.mockRestore()
985 })
986 })