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

optional-path-params.test.tsx

1,075 lines31.2 KB

1import { afterEach, describe, expect, it, vi } from 'vitest'
2import {
3 cleanup,
4 fireEvent,
5 render,
6 screen,
7 waitFor,
8} from '@solidjs/testing-library'
9import {
10 Link,
11 Outlet,
12 RouterProvider,
13 createRootRoute,
14 createRoute,
15 createRouter,
16 useNavigate,
17} from '../src'
18​
19describe('Solid Router - Optional Path Parameters', () => {
20 afterEach(() => {
21 cleanup()
22 vi.clearAllMocks()
23 window.history.replaceState(null, 'root', '/')
24 })
25​
26 describe('Route matching with optional parameters', () => {
27 it('should match route with no optional parameters', async () => {
28 const rootRoute = createRootRoute()
29 const postsRoute = createRoute({
30 getParentRoute: () => rootRoute,
31 path: '/posts/{-$category}/{-$slug}',
32 component: () => {
33 const params = postsRoute.useParams()
34 return (
35 <div>
36 <h1>Posts</h1>
37 <div data-testid="params">{JSON.stringify(params())}</div>
38 </div>
39 )
40 },
41 })
42 window.history.replaceState({}, '', '/posts')
43​
44 const router = createRouter({
45 routeTree: rootRoute.addChildren([postsRoute]),
46 })
47​
48 render(() => <RouterProvider router={router} />)
49 await router.load()
50​
51 const paramsElement = await screen.findByTestId('params')
52 expect(JSON.parse(paramsElement.textContent)).toEqual({})
53 })
54​
55 it('should match route with one optional parameter', async () => {
56 const rootRoute = createRootRoute()
57 const postsRoute = createRoute({
58 getParentRoute: () => rootRoute,
59 path: '/posts/{-$category}/{-$slug}',
60 component: () => {
61 const params = postsRoute.useParams()
62 return (
63 <div>
64 <h1>Posts</h1>
65 <div data-testid="params">{JSON.stringify(params())}</div>
66 </div>
67 )
68 },
69 })
70 window.history.replaceState({}, '', '/posts/tech')
71​
72 const router = createRouter({
73 routeTree: rootRoute.addChildren([postsRoute]),
74 })
75​
76 render(() => <RouterProvider router={router} />)
77 await router.load()
78​
79 const paramsElement = await screen.findByTestId('params')
80 expect(JSON.parse(paramsElement.textContent)).toEqual({
81 category: 'tech',
82 })
83 })
84​
85 it('should match route with all optional parameters', async () => {
86 const rootRoute = createRootRoute()
87 const postsRoute = createRoute({
88 getParentRoute: () => rootRoute,
89 path: '/posts/{-$category}/{-$slug}',
90 component: () => {
91 const params = postsRoute.useParams()
92 return (
93 <div>
94 <h1>Posts</h1>
95 <div data-testid="params">{JSON.stringify(params())}</div>
96 </div>
97 )
98 },
99 })
100 window.history.replaceState({}, '', '/posts/tech/hello-world')
101​
102 const router = createRouter({
103 routeTree: rootRoute.addChildren([postsRoute]),
104 })
105​
106 render(() => <RouterProvider router={router} />)
107 await router.load()
108​
109 const paramsElement = await screen.findByTestId('params')
110 expect(JSON.parse(paramsElement.textContent)).toEqual({
111 category: 'tech',
112 slug: 'hello-world',
113 })
114 })
115​
116 it.each([
117 { path: '/users/123', expectedParams: { id: '123' } },
118 {
119 path: '/users/123/settings',
120 expectedParams: { id: '123', tab: 'settings' },
121 },
122 ])(
123 'should handle mixed required and optional parameters: $path',
124 async ({ path, expectedParams }) => {
125 const rootRoute = createRootRoute()
126 const usersRoute = createRoute({
127 getParentRoute: () => rootRoute,
128 path: '/users/$id/{-$tab}',
129 component: () => {
130 const params = usersRoute.useParams()
131 return (
132 <div>
133 <h1>User Profile</h1>
134 <div data-testid="params">{JSON.stringify(params())}</div>
135 </div>
136 )
137 },
138 })
139 window.history.replaceState({}, '', path)
140​
141 const router = createRouter({
142 routeTree: rootRoute.addChildren([usersRoute]),
143 })
144​
145 render(() => <RouterProvider router={router} />)
146 await router.load()
147​
148 const paramsElement = await screen.findByTestId('params')
149 expect(JSON.parse(paramsElement.textContent)).toEqual(expectedParams)
150 },
151 )
152​
153 it.each([
154 {
155 path: '/',
156 expectedLocale: 'en' as const,
157 },
158 {
159 path: '/en',
160 expectedLocale: 'en' as const,
161 },
162 {
163 path: '/fr',
164 expectedLocale: 'fr' as const,
165 },
166 ])(
167 'should correctly render matches with and without optional parameter',
168 async ({ path, expectedLocale }) => {
169 const content = {
170 en: {
171 title: 'About Us',
172 description: 'Learn more about our company.',
173 },
174 fr: {
175 title: 'À Propos',
176 description: 'En savoir plus sur notre entreprise.',
177 },
178 es: {
179 title: 'Acerca de',
180 description: 'Conoce más sobre nuestra empresa.',
181 },
182 } as const
183​
184 const rootRoute = createRootRoute()
185 const localeRoute = createRoute({
186 getParentRoute: () => rootRoute,
187 path: '/{-$locale}',
188 beforeLoad: ({ params }) => {
189 const currentLocale = (params.locale ||
190 'en') as keyof typeof content
191​
192 return {
193 content: content[currentLocale],
194 }
195 },
196 })
197​
198 const indexRoute = createRoute({
199 getParentRoute: () => localeRoute,
200 path: '/',
201 component: () => {
202 const context = indexRoute.useRouteContext()
203 return (
204 <div data-testid="index-content">
205 <h1 data-testid="index-title">{context().content.title}</h1>
206 <p data-testid="index-description">
207 {context().content.description}
208 </p>
209 </div>
210 )
211 },
212 })
213​
214 window.history.replaceState({}, '', path)
215​
216 const router = createRouter({
217 routeTree: rootRoute.addChildren([
218 localeRoute.addChildren([indexRoute]),
219 ]),
220 })
221​
222 render(() => <RouterProvider router={router} />)
223 await router.load()
224​
225 await screen.findByTestId('index-content')
226 const titleElement = screen.getByTestId('index-title')
227 const descriptionElement = screen.getByTestId('index-description')
228 expect(titleElement).toHaveTextContent(content[expectedLocale].title)
229 expect(descriptionElement).toHaveTextContent(
230 content[expectedLocale].description,
231 )
232 },
233 )
234 })
235​
236 describe('required and optional parameters on the same level', () => {
237 async function setupTestRouter() {
238 const rootRoute = createRootRoute()
239​
240 const indexRoute = createRoute({
241 getParentRoute: () => rootRoute,
242 path: '/',
243 component: () => {
244 return (
245 <div data-testid="index-route-component">
246 <h1>index</h1>
247 <Link
248 data-testid="reports-optional-param-link"
249 params={{ adminLevelId: 'asdf' }}
250 to="/admin-levels/{-$adminLevelId}/reports"
251 >
252 navigate to reports with optional param
253 </Link>
254 </div>
255 )
256 },
257 })
258​
259 const adminLevelsRoutes = createRoute({
260 getParentRoute: () => rootRoute,
261​
262 path: 'admin-levels',
263 component: () => (
264 <div data-testid="admin-levels-route-component">
265 <h1>admin-levels</h1>
266 <Outlet />
267 </div>
268 ),
269 })
270​
271 const requiredParamRoute = createRoute({
272 getParentRoute: () => adminLevelsRoutes,
273 path: '$adminLevelId',
274 component: () => (
275 <div data-testid="admin-levels-route-required-param-route-component">
276 <h1>Required Param Route</h1>
277 <Outlet />
278 </div>
279 ),
280 })
281​
282 const requiredParamIndexRoute = createRoute({
283 getParentRoute: () => requiredParamRoute,
284 path: '/',
285 component: () => (
286 <div data-testid="admin-levels-route-required-param-index-route-component">
287 <h1>Required Param Route Index</h1>
288 </div>
289 ),
290 })
291​
292 const optionalParamRoute = createRoute({
293 getParentRoute: () => adminLevelsRoutes,
294 path: '{-$adminLevelId}',
295 component: () => (
296 <div data-testid="admin-levels-route-optional-param-route-component">
297 <h1>Optional Param Route</h1>
298 <Outlet />
299 </div>
300 ),
301 })
302​
303 const reportsRoute = createRoute({
304 getParentRoute: () => optionalParamRoute,
305 path: 'reports',
306 component: () => (
307 <div data-testid="reports-route-component">
308 <h1>Reports</h1>
309 <Link
310 data-testid="navigate-to-required-param-link"
311 to="/admin-levels/$adminLevelId"
312 params={{ adminLevelId: 'asdf' }}
313 >
314 navigate to required param route
315 </Link>
316 <Outlet />
317 </div>
318 ),
319 })
320​
321 const router = createRouter({
322 routeTree: rootRoute.addChildren([
323 indexRoute,
324 adminLevelsRoutes.addChildren([
325 requiredParamRoute.addChildren([requiredParamIndexRoute]),
326 optionalParamRoute.addChildren([reportsRoute]),
327 ]),
328 ]),
329 })
330​
331 render(() => <RouterProvider router={router} />)
332 await router.load()
333 return router
334 }
335​
336 it('direct visit', async () => {
337 window.history.replaceState({}, '', 'admin-levels/asdf')
338 await setupTestRouter()
339​
340 expect(
341 await screen.findByTestId(
342 'admin-levels-route-required-param-route-component',
343 ),
344 ).toBeInTheDocument()
345 expect(
346 await screen.findByTestId(
347 'admin-levels-route-required-param-index-route-component',
348 ),
349 ).toBeInTheDocument()
350 })
351​
352 it('client-side navigation', async () => {
353 window.history.replaceState({}, '', '/')
354​
355 await setupTestRouter()
356​
357 expect(
358 await screen.findByTestId('index-route-component'),
359 ).toBeInTheDocument()
360 const reportsLink = await screen.findByTestId(
361 'reports-optional-param-link',
362 )
363 fireEvent.click(reportsLink)
364​
365 expect(
366 await screen.findByTestId('reports-route-component'),
367 ).toBeInTheDocument()
368 const requiredParamLink = await screen.findByTestId(
369 'navigate-to-required-param-link',
370 )
371 fireEvent.click(requiredParamLink)
372​
373 expect(
374 await screen.findByTestId(
375 'admin-levels-route-required-param-route-component',
376 ),
377 ).toBeInTheDocument()
378​
379 expect(
380 await screen.findByTestId(
381 'admin-levels-route-required-param-index-route-component',
382 ),
383 ).toBeInTheDocument()
384 })
385 })
386​
387 describe('Link component with optional parameters', () => {
388 it('should generate correct href for optional parameters', async () => {
389 const rootRoute = createRootRoute()
390 const indexRoute = createRoute({
391 getParentRoute: () => rootRoute,
392 path: '/',
393 component: () => (
394 <>
395 <Link to="/posts/{-$category}/{-$slug}" data-testid="posts-link">
396 All Posts
397 </Link>
398 <Link
399 to="/posts/{-$category}/{-$slug}"
400 params={{ category: 'tech' }}
401 data-testid="tech-link"
402 >
403 Tech Posts
404 </Link>
405 <Link
406 to="/posts/{-$category}/{-$slug}"
407 params={{ category: 'tech', slug: 'hello-world' }}
408 data-testid="specific-link"
409 >
410 Specific Post
411 </Link>
412 <Link
413 to="/posts/{-$category}/{-$slug}"
414 params={{}}
415 data-testid="empty-params-link"
416 >
417 Empty Params
418 </Link>
419 </>
420 ),
421 })
422​
423 const postsRoute = createRoute({
424 getParentRoute: () => rootRoute,
425 path: '/posts/{-$category}/{-$slug}',
426 component: () => <div>Posts</div>,
427 })
428​
429 const router = createRouter({
430 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
431 })
432​
433 render(() => <RouterProvider router={router} />)
434​
435 const postsLink = await screen.findByTestId('posts-link')
436 const techLink = await screen.findByTestId('tech-link')
437 const specificLink = await screen.findByTestId('specific-link')
438 const emptyParamsLink = await screen.findByTestId('empty-params-link')
439​
440 expect(postsLink).toHaveAttribute('href', '/posts')
441 expect(techLink).toHaveAttribute('href', '/posts/tech')
442 expect(specificLink).toHaveAttribute('href', '/posts/tech/hello-world')
443 expect(emptyParamsLink).toHaveAttribute('href', '/posts')
444 })
445​
446 it('should navigate correctly with optional parameters', async () => {
447 const rootRoute = createRootRoute({
448 component: () => {
449 return (
450 <div>
451 <h1>Root Layout</h1>
452 <Link to="/" data-testid="home-link">
453 Home
454 </Link>
455 <Outlet />
456 </div>
457 )
458 },
459 })
460 const indexRoute = createRoute({
461 getParentRoute: () => rootRoute,
462 path: '/',
463 component: () => (
464 <>
465 <h1 data-testid="home-heading">Home</h1>
466 <Link to="/posts/{-$category}/{-$slug}" data-testid="posts-link">
467 All Posts
468 </Link>
469 <Link
470 to="/posts/{-$category}/{-$slug}"
471 params={{ category: 'tech' }}
472 data-testid="tech-link"
473 >
474 Tech Posts
475 </Link>
476 </>
477 ),
478 })
479​
480 const postsRoute = createRoute({
481 getParentRoute: () => rootRoute,
482 path: '/posts/{-$category}/{-$slug}',
483 component: () => {
484 const params = postsRoute.useParams()
485 return (
486 <div>
487 <h1>Posts</h1>
488 <div data-testid="params">{JSON.stringify(params())}</div>
489 </div>
490 )
491 },
492 })
493​
494 const router = createRouter({
495 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
496 })
497​
498 render(() => <RouterProvider router={router} />)
499 await router.load()
500​
501 {
502 await expect(
503 screen.findByTestId('home-heading'),
504 ).resolves.toBeInTheDocument()
505 // Test navigation to /posts
506 const postsLink = await screen.findByTestId('posts-link')
507 fireEvent.click(postsLink)
508​
509 await expect(screen.findByText('Posts')).resolves.toBeInTheDocument()
510 const paramsElement = await screen.findByTestId('params')
511 expect(JSON.parse(paramsElement.textContent)).toEqual({})
512 expect(router.state.location.pathname).toBe('/posts')
513 }
514​
515 {
516 // Navigate back
517 const homeLink = await screen.findByTestId('home-link')
518 fireEvent.click(homeLink)
519 await expect(
520 screen.findByTestId('home-heading'),
521 ).resolves.toBeInTheDocument()
522 }
523​
524 // test with parameters
525 {
526 const techLink = await screen.findByTestId('tech-link')
527 fireEvent.click(techLink)
528​
529 await expect(screen.findByText('Posts')).resolves.toBeInTheDocument()
530 const updatedParamsElement = await screen.findByTestId('params')
531 expect(JSON.parse(updatedParamsElement.textContent)).toEqual({
532 category: 'tech',
533 })
534 expect(router.state.location.pathname).toBe('/posts/tech')
535 }
536 })
537​
538 it('should handle optional parameters with prefix and suffix', async () => {
539 const rootRoute = createRootRoute()
540 const indexRoute = createRoute({
541 getParentRoute: () => rootRoute,
542 path: '/',
543 component: () => (
544 <>
545 <Link to="/files/prefix{-$name}.txt" data-testid="files-link">
546 All Files
547 </Link>
548 <Link
549 to="/files/prefix{-$name}.txt"
550 params={{ name: 'document' }}
551 data-testid="doc-link"
552 >
553 Document
554 </Link>
555 </>
556 ),
557 })
558​
559 const filesRoute = createRoute({
560 getParentRoute: () => rootRoute,
561 path: '/files/prefix{-$name}.txt',
562 component: () => {
563 const params = filesRoute.useParams()
564 return (
565 <div>
566 <h1>Files</h1>
567 <div data-testid="params">{JSON.stringify(params())}</div>
568 </div>
569 )
570 },
571 })
572​
573 const router = createRouter({
574 routeTree: rootRoute.addChildren([indexRoute, filesRoute]),
575 })
576​
577 render(() => <RouterProvider router={router} />)
578​
579 const filesLink = await screen.findByTestId('files-link')
580 const docLink = await screen.findByTestId('doc-link')
581​
582 expect(filesLink).toHaveAttribute('href', '/files/prefix.txt')
583 expect(docLink).toHaveAttribute('href', '/files/prefixdocument.txt')
584 })
585 })
586​
587 describe('useNavigate with optional parameters', () => {
588 it('should navigate with optional parameters programmatically', async () => {
589 const rootRoute = createRootRoute()
590 const postsRoute = createRoute({
591 getParentRoute: () => rootRoute,
592 path: '/posts/{-$category}/{-$slug}',
593 component: Component,
594 })
595​
596 function Component() {
597 const navigate = useNavigate()
598 const params = postsRoute.useParams()
599​
600 return (
601 <div>
602 <div data-testid="params">{JSON.stringify(params())}</div>
603 <button
604 data-testid="navigate-all"
605 onClick={() =>
606 navigate({
607 to: '/posts/{-$category}/{-$slug}',
608 params: false,
609 })
610 }
611 >
612 All Posts
613 </button>
614 <button
615 data-testid="navigate-tech"
616 onClick={() =>
617 navigate({
618 to: '/posts/{-$category}/{-$slug}',
619 params: { category: 'tech', slug: undefined },
620 })
621 }
622 >
623 Tech Posts
624 </button>
625 <button
626 data-testid="navigate-specific"
627 onClick={() =>
628 navigate({
629 to: '/posts/{-$category}/{-$slug}',
630 params: { category: 'tech', slug: 'hello-world' },
631 })
632 }
633 >
634 Specific Post
635 </button>
636 </div>
637 )
638 }
639 // Start at a specific post
640 window.history.replaceState({}, '', '/posts/tech/hello-world')
641​
642 const router = createRouter({
643 routeTree: rootRoute.addChildren([postsRoute]),
644 })
645​
646 render(() => <RouterProvider router={router} />)
647​
648 // Test navigation scenarios
649 const navigateAll = await screen.findByTestId('navigate-all')
650 const navigateTech = await screen.findByTestId('navigate-tech')
651 const navigateSpecific = await screen.findByTestId('navigate-specific')
652​
653 fireEvent.click(navigateAll)
654 expect(router.state.location.pathname).toBe('/posts')
655​
656 fireEvent.click(navigateTech)
657 expect(router.state.location.pathname).toBe('/posts/tech')
658​
659 fireEvent.click(navigateSpecific)
660 expect(router.state.location.pathname).toBe('/posts/tech/hello-world')
661 })
662​
663 it('should handle relative navigation with optional parameters', async () => {
664 const rootRoute = createRootRoute()
665 const postsRoute = createRoute({
666 getParentRoute: () => rootRoute,
667 path: '/posts/{-$category}',
668 component: Component,
669 })
670​
671 function Component() {
672 const navigate = useNavigate()
673 const params = postsRoute.useParams()
674​
675 return (
676 <div>
677 <h1>Posts</h1>
678 <div data-testid="params">{JSON.stringify(params())}</div>
679 <button
680 data-testid="add-category"
681 onClick={() =>
682 navigate({ to: '.', params: { category: 'tech' } })
683 }
684 >
685 Add Category
686 </button>
687 <button
688 data-testid="remove-category"
689 onClick={() => navigate({ to: '.', params: false })}
690 >
691 Remove Category
692 </button>
693 </div>
694 )
695 }
696 window.history.replaceState({}, '', '/posts')
697​
698 const router = createRouter({
699 routeTree: rootRoute.addChildren([postsRoute]),
700 })
701​
702 render(() => <RouterProvider router={router} />)
703 await router.load()
704​
705 expect(await screen.findByTestId('params')).toHaveTextContent(
706 JSON.stringify({}),
707 )
708​
709 const addCategoryBtn = await screen.findByTestId('add-category')
710​
711 // Add category
712 fireEvent.click(addCategoryBtn)
713 await waitFor(() => {
714 expect(screen.getByTestId('params')).toHaveTextContent(
715 JSON.stringify({ category: 'tech' }),
716 )
717 })
718 expect(router.state.location.pathname).toBe('/posts/tech')
719​
720 // Remove category - get fresh reference after navigation
721 const removeCategoryBtn = await screen.findByTestId('remove-category')
722 fireEvent.click(removeCategoryBtn)
723 await waitFor(() => {
724 expect(router.state.location.pathname).toBe('/posts')
725 })
726 await waitFor(() => {
727 expect(screen.getByTestId('params')).toHaveTextContent(
728 JSON.stringify({}),
729 )
730 })
731 })
732 })
733​
734 describe('complex routing scenarios', () => {
735 it.each([
736 {
737 path: '/posts',
738 expected: {
739 posts: {
740 rendered: true,
741 category: 'undefined',
742 },
743 post: {
744 rendered: false,
745 },
746 },
747 },
748 {
749 path: '/posts/tech',
750 expected: {
751 posts: {
752 rendered: true,
753 category: 'tech',
754 },
755 post: {
756 rendered: false,
757 },
758 },
759 },
760 {
761 path: '/posts/tech/hello-world',
762 expected: {
763 posts: {
764 rendered: true,
765 category: 'tech',
766 },
767 post: {
768 rendered: true,
769 slug: 'hello-world',
770 },
771 },
772 },
773 ])(
774 'should handle nested routes with optional parameters: $path',
775 async ({ path, expected }) => {
776 const rootRoute = createRootRoute()
777 const postsRoute = createRoute({
778 getParentRoute: () => rootRoute,
779 path: '/posts/{-$category}',
780 component: () => {
781 const params = postsRoute.useParams()
782 return (
783 <div>
784 <h1>Posts Layout</h1>
785 <div data-testid="category-param">
786 {params().category ?? 'undefined'}
787 </div>
788 <Outlet />
789 </div>
790 )
791 },
792 })
793​
794 const postRoute = createRoute({
795 getParentRoute: () => postsRoute,
796 path: '/{-$slug}',
797 component: () => {
798 const params = postRoute.useParams()
799 return (
800 <div>
801 <h2>Post Detail</h2>
802 <div data-testid="slug-param">{params().slug ?? undefined}</div>
803 </div>
804 )
805 },
806 })
807​
808 window.history.replaceState({}, '', path)
809​
810 const router = createRouter({
811 routeTree: rootRoute.addChildren([
812 postsRoute.addChildren([postRoute]),
813 ]),
814 })
815​
816 render(() => <RouterProvider router={router} />)
817 await router.load()
818 if (expected.posts.rendered) {
819 const categoryParam = await screen.findByTestId('category-param')
820 expect(categoryParam).toHaveTextContent(expected.posts.category)
821 }
822 if (expected.post.rendered) {
823 const slugParam = await screen.findByTestId('slug-param')
824 expect(slugParam).toHaveTextContent(expected.post.slug!)
825 }
826 },
827 )
828​
829 it('should work with search parameters', async () => {
830 const rootRoute = createRootRoute()
831 const postsRoute = createRoute({
832 getParentRoute: () => rootRoute,
833 path: '/posts/{-$category}',
834 validateSearch: (search) => ({
835 page: Number(search.page) || 1,
836 sort: (search.sort as string) || 'date',
837 }),
838 component: Component,
839 })
840​
841 function Component() {
842 const params = postsRoute.useParams()
843 const search = postsRoute.useSearch()
844 return (
845 <div>
846 <h1>Posts</h1>
847 <div data-testid="params">{JSON.stringify(params())}</div>
848 <div data-testid="search">{JSON.stringify(search())}</div>
849 </div>
850 )
851 }
852​
853 window.history.replaceState({}, '', '/posts/tech?page=2&sort=title')
854 const router = createRouter({
855 routeTree: rootRoute.addChildren([postsRoute]),
856 })
857​
858 render(() => <RouterProvider router={router} />)
859 await router.load()
860​
861 const paramsElement = await screen.findByTestId('params')
862 const searchElement = await screen.findByTestId('search')
863​
864 expect(JSON.parse(paramsElement.textContent)).toEqual({
865 category: 'tech',
866 })
867 expect(JSON.parse(searchElement.textContent)).toEqual({
868 page: 2,
869 sort: 'title',
870 })
871 })
872​
873 it.each([
874 { path: '/', expectedParams: {} },
875 { path: '/2023', expectedParams: { year: '2023' } },
876 { path: '/2023/12', expectedParams: { year: '2023', month: '12' } },
877 {
878 path: '/2023/12/25',
879 expectedParams: { year: '2023', month: '12', day: '25' },
880 },
881 ])(
882 'should handle multiple consecutive optional parameters: $path',
883 async ({ path, expectedParams }) => {
884 const rootRoute = createRootRoute()
885 const dateRoute = createRoute({
886 getParentRoute: () => rootRoute,
887 path: '/{-$year}/{-$month}/{-$day}',
888 component: () => {
889 const params = dateRoute.useParams()
890 return (
891 <div>
892 <h1>Date Route</h1>
893 <div data-testid="params">{JSON.stringify(params())}</div>
894 </div>
895 )
896 },
897 })
898​
899 window.history.replaceState({}, '', path)
900​
901 const router = createRouter({
902 routeTree: rootRoute.addChildren([dateRoute]),
903 })
904​
905 render(() => <RouterProvider router={router} />)
906 await router.load()
907​
908 const paramsElement = await screen.findByTestId('params')
909 expect(JSON.parse(paramsElement.textContent)).toEqual(expectedParams)
910 },
911 )
912​
913 it.each([
914 {
915 path: '/chambres',
916 expected: {
917 rooms: 'chambres',
918 locale: 'undefined',
919 },
920 },
921 {
922 path: '/fr/chambres',
923 expected: {
924 rooms: 'chambres',
925 locale: 'fr',
926 },
927 },
928 {
929 path: '/rooms',
930 expected: {
931 rooms: 'rooms',
932 locale: 'undefined',
933 },
934 },
935 {
936 path: '/en/rooms',
937 expected: {
938 rooms: 'rooms',
939 locale: 'en',
940 },
941 },
942 ])(
943 'should handle routes with required param after optional param: $path',
944 async ({ path, expected }) => {
945 const rootRoute = createRootRoute()
946 const roomsRoute = createRoute({
947 getParentRoute: () => rootRoute,
948 path: '/{-$locale}/$rooms',
949 component: () => {
950 const params = roomsRoute.useParams()
951 return (
952 <div>
953 <h1>Rooms</h1>
954 <div data-testid="locale-param">
955 {params().locale ?? 'undefined'}
956 </div>
957 <div data-testid="rooms-param">
958 {params().rooms ?? 'undefined'}
959 </div>
960 <Outlet />
961 </div>
962 )
963 },
964 })
965​
966 window.history.replaceState({}, '', path)
967​
968 const router = createRouter({
969 routeTree: rootRoute.addChildren([roomsRoute]),
970 })
971​
972 render(() => <RouterProvider router={router} />)
973 await router.load()
974 const roomsParam = await screen.findByTestId('rooms-param')
975 expect(roomsParam).toHaveTextContent(expected.rooms)
976 const localeParam = await screen.findByTestId('locale-param')
977 expect(localeParam).toHaveTextContent(expected.locale)
978 },
979 )
980 })
981​
982 describe('edge cases and error handling', () => {
983 it('should handle optional parameters with loaders', async () => {
984 const mockLoader = vi.fn((opts) => {
985 return Promise.resolve({
986 category: opts.params.category || 'all',
987 data: `Data for ${opts.params.category || 'all'}`,
988 })
989 })
990​
991 const rootRoute = createRootRoute()
992 const postsRoute = createRoute({
993 getParentRoute: () => rootRoute,
994 path: '/posts/{-$category}',
995 loader: mockLoader,
996 component: () => {
997 const data = postsRoute.useLoaderData()
998 const params = postsRoute.useParams()
999 return (
1000 <div>
1001 <h1>Posts</h1>
1002 <div data-testid="params">{JSON.stringify(params())}</div>
1003 <div data-testid="loader-data">{JSON.stringify(data())}</div>
1004 </div>
1006 },
1007 })
1008 window.history.replaceState({}, '', '/posts')
1009​
1010 const router = createRouter({
1011 routeTree: rootRoute.addChildren([postsRoute]),
1012 })
1013​
1014 // Test without category
1015 render(() => <RouterProvider router={router} />)
1016 await router.load()
1017​
1018 await expect(screen.findByText('Posts')).resolves.toBeInTheDocument()
1019 const paramsElement = await screen.findByTestId('params')
1020 const loaderDataElement = await screen.findByTestId('loader-data')
1021​
1022 expect(JSON.parse(paramsElement.textContent)).toEqual({})
1023 expect(JSON.parse(loaderDataElement.textContent)).toEqual({
1024 category: 'all',
1025 data: 'Data for all',
1026 })
1027​
1028 expect(mockLoader).toHaveBeenCalledWith(
1029 expect.objectContaining({
1030 params: {},
1031 }),
1033 })
1034​
1035 it('should handle beforeLoad with optional parameters', async () => {
1036 const mockBeforeLoad = vi.fn((opts) => {
1037 return {
1038 category: opts.params.category || 'default',
1039 timestamp: Date.now(),
1041 })
1042​
1043 const rootRoute = createRootRoute()
1044 const postsRoute = createRoute({
1045 getParentRoute: () => rootRoute,
1046 path: '/posts/{-$category}',
1047 beforeLoad: mockBeforeLoad,
1048 component: () => {
1049 const params = postsRoute.useParams()
1050 return (
1051 <div>
1052 <h1>Posts</h1>
1053 <div data-testid="params">{JSON.stringify(params())}</div>
1054 </div>
1056 },
1057 })
1058 window.history.replaceState({}, '', '/posts/tech')
1059​
1060 const router = createRouter({
1061 routeTree: rootRoute.addChildren([postsRoute]),
1062 })
1063​
1064 render(() => <RouterProvider router={router} />)
1065​
1066 await expect(screen.findByText('Posts')).resolves.toBeInTheDocument()
1067​
1068 expect(mockBeforeLoad).toHaveBeenCalledWith(
1069 expect.objectContaining({
1070 params: { category: 'tech' },
1071 }),
1073 })
1074 })