Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

ClientOnly.test.tsx

89 lines2.4 KB

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 }
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})