Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { cleanup, render, screen } from '@solidjs/testing-library'
3import {
4 RouterProvider,
5 createMemoryHistory,
6 createRootRoute,
7 createRoute,
8 createRouter,
9} from '../src'
10import { ClientOnly } from '../src/ClientOnly'
11import type { RouterHistory } from '../src'
12β
13afterEach(() => {
14 vi.resetAllMocks()
15 cleanup()
16})
17β
18function createTestRouter(initialHistory?: RouterHistory) {
19 const history =
20 initialHistory ?? createMemoryHistory({ initialEntries: ['/'] })
21β
22 const rootRoute = createRootRoute({})
23β
24 const indexRoute = createRoute({
25 getParentRoute: () => rootRoute,
26 path: '/',
27 component: () => (
28 <div>
29 <p>Index Route</p>
30 <ClientOnly fallback={<div data-testid="loading">Loading...</div>}>
31 <div data-testid="client-only-content">Client Only Content</div>
32 </ClientOnly>
33 </div>
34 ),
35 })
36β
37 const routeTree = rootRoute.addChildren([indexRoute])
38 const router = createRouter({ routeTree, history })
39β
40 return {
41 router,
42 routes: { indexRoute },
43 }
44}
45β
46describe('ClientOnly', () => {
47 beforeEach(() => {
48 window.scrollTo = vi.fn()
49 })
50β
51 // Clear mocks after each test to prevent interference
52 afterEach(() => {
53 vi.clearAllMocks()
54 })
55β
56 it('should render client content after hydration', async () => {
57 const { router } = createTestRouter()
58 await router.load()
59β
60 // Mock useSyncExternalStore to simulate hydration
61 // vi.spyOn(Solid, 'createEffect').mockImplementation(() => true)
62β
63 render(() => <RouterProvider router={router} />)
64β
65 expect(await screen.findByTestId('client-only-content')).toBeInTheDocument()
66 expect(screen.queryByTestId('loading')).not.toBeInTheDocument()
67 })
68β
69 it('should handle navigation with client-only content', async () => {
70 const { router } = createTestRouter()
71 await router.load()
72β
73 // Simulate hydration
74 // vi.spyOn(Solid, 'createEffect').mockImplementation(() => true)
75β
76 // Re-render after hydration
77 render(() => <RouterProvider router={router} />)
78β
79 // Content should be visible before navigation
80 expect(await screen.findByTestId('client-only-content')).toBeInTheDocument()
81β
82 // Navigate to a different route and back
83 await router.navigate({ to: '/other' })
84 await router.navigate({ to: '/' })
85β
86 // Content should still be visible after navigation
87 expect(await screen.findByTestId('client-only-content')).toBeInTheDocument()
88 })
89})