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

optional-path-params.test.tsx

1,080 lines31.3 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')
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 await fireEvent.click(navigateAll)
651 await waitFor(() => {
652 expect(router.state.location.pathname).toBe('/posts')
653 })
654​
655 const navigateTech = await screen.findByTestId('navigate-tech')
656 await fireEvent.click(navigateTech)
657 await waitFor(() => {
658 expect(router.state.location.pathname).toBe('/posts/tech')
659 })
660​
661 const navigateSpecific = await screen.findByTestId('navigate-specific')
662 await fireEvent.click(navigateSpecific)
663 await waitFor(() => {
664 expect(router.state.location.pathname).toBe('/posts/tech/hello-world')
665 })
666 })
667​
668 it('should handle relative navigation with optional parameters', async () => {
669 const rootRoute = createRootRoute()
670 const postsRoute = createRoute({
671 getParentRoute: () => rootRoute,
672 path: '/posts/{-$category}',
673 component: Component,
674 })
675​
676 function Component() {
677 const navigate = useNavigate()
678 const params = postsRoute.useParams()
679​
680 return (
681 <div>
682 <h1>Posts</h1>
683 <div data-testid="params">{JSON.stringify(params())}</div>
684 <button
685 data-testid="add-category"
686 onClick={() =>
687 navigate({ to: '.', params: { category: 'tech' } })
688 }
689 >
690 Add Category
691 </button>
692 <button
693 data-testid="remove-category"
694 onClick={() => navigate({ to: '.', params: false })}
695 >
696 Remove Category
697 </button>
698 </div>
699 )
700 }
701 window.history.replaceState({}, '', '/posts')
702​
703 const router = createRouter({
704 routeTree: rootRoute.addChildren([postsRoute]),
705 })
706​
707 render(() => <RouterProvider router={router} />)
708 await router.load()
709​
710 expect(await screen.findByTestId('params')).toHaveTextContent(
711 JSON.stringify({}),
712 )
713​
714 const addCategoryBtn = await screen.findByTestId('add-category')
715​
716 // Add category
717 fireEvent.click(addCategoryBtn)
718 await waitFor(() => {
719 expect(screen.getByTestId('params')).toHaveTextContent(
720 JSON.stringify({ category: 'tech' }),
721 )
722 })
723 expect(router.state.location.pathname).toBe('/posts/tech')
724​
725 // Remove category - get fresh reference after navigation
726 const removeCategoryBtn = await screen.findByTestId('remove-category')
727 fireEvent.click(removeCategoryBtn)
728 await waitFor(() => {
729 expect(router.state.location.pathname).toBe('/posts')
730 })
731 await waitFor(() => {
732 expect(screen.getByTestId('params')).toHaveTextContent(
733 JSON.stringify({}),
734 )
735 })
736 })
737 })
738​
739 describe('complex routing scenarios', () => {
740 it.each([
741 {
742 path: '/posts',
743 expected: {
744 posts: {
745 rendered: true,
746 category: 'undefined',
747 },
748 post: {
749 rendered: false,
750 },
751 },
752 },
753 {
754 path: '/posts/tech',
755 expected: {
756 posts: {
757 rendered: true,
758 category: 'tech',
759 },
760 post: {
761 rendered: false,
762 },
763 },
764 },
765 {
766 path: '/posts/tech/hello-world',
767 expected: {
768 posts: {
769 rendered: true,
770 category: 'tech',
771 },
772 post: {
773 rendered: true,
774 slug: 'hello-world',
775 },
776 },
777 },
778 ])(
779 'should handle nested routes with optional parameters: $path',
780 async ({ path, expected }) => {
781 const rootRoute = createRootRoute()
782 const postsRoute = createRoute({
783 getParentRoute: () => rootRoute,
784 path: '/posts/{-$category}',
785 component: () => {
786 const params = postsRoute.useParams()
787 return (
788 <div>
789 <h1>Posts Layout</h1>
790 <div data-testid="category-param">
791 {params().category ?? 'undefined'}
792 </div>
793 <Outlet />
794 </div>
795 )
796 },
797 })
798​
799 const postRoute = createRoute({
800 getParentRoute: () => postsRoute,
801 path: '/{-$slug}',
802 component: () => {
803 const params = postRoute.useParams()
804 return (
805 <div>
806 <h2>Post Detail</h2>
807 <div data-testid="slug-param">{params().slug ?? undefined}</div>
808 </div>
809 )
810 },
811 })
812​
813 window.history.replaceState({}, '', path)
814​
815 const router = createRouter({
816 routeTree: rootRoute.addChildren([
817 postsRoute.addChildren([postRoute]),
818 ]),
819 })
820​
821 render(() => <RouterProvider router={router} />)
822 await router.load()
823 if (expected.posts.rendered) {
824 const categoryParam = await screen.findByTestId('category-param')
825 expect(categoryParam).toHaveTextContent(expected.posts.category)
826 }
827 if (expected.post.rendered) {
828 const slugParam = await screen.findByTestId('slug-param')
829 expect(slugParam).toHaveTextContent(expected.post.slug!)
830 }
831 },
832 )
833​
834 it('should work with search parameters', async () => {
835 const rootRoute = createRootRoute()
836 const postsRoute = createRoute({
837 getParentRoute: () => rootRoute,
838 path: '/posts/{-$category}',
839 validateSearch: (search) => ({
840 page: Number(search.page) || 1,
841 sort: (search.sort as string) || 'date',
842 }),
843 component: Component,
844 })
845​
846 function Component() {
847 const params = postsRoute.useParams()
848 const search = postsRoute.useSearch()
849 return (
850 <div>
851 <h1>Posts</h1>
852 <div data-testid="params">{JSON.stringify(params())}</div>
853 <div data-testid="search">{JSON.stringify(search())}</div>
854 </div>
855 )
856 }
857​
858 window.history.replaceState({}, '', '/posts/tech?page=2&sort=title')
859 const router = createRouter({
860 routeTree: rootRoute.addChildren([postsRoute]),
861 })
862​
863 render(() => <RouterProvider router={router} />)
864 await router.load()
865​
866 const paramsElement = await screen.findByTestId('params')
867 const searchElement = await screen.findByTestId('search')
868​
869 expect(JSON.parse(paramsElement.textContent)).toEqual({
870 category: 'tech',
871 })
872 expect(JSON.parse(searchElement.textContent)).toEqual({
873 page: 2,
874 sort: 'title',
875 })
876 })
877​
878 it.each([
879 { path: '/', expectedParams: {} },
880 { path: '/2023', expectedParams: { year: '2023' } },
881 { path: '/2023/12', expectedParams: { year: '2023', month: '12' } },
882 {
883 path: '/2023/12/25',
884 expectedParams: { year: '2023', month: '12', day: '25' },
885 },
886 ])(
887 'should handle multiple consecutive optional parameters: $path',
888 async ({ path, expectedParams }) => {
889 const rootRoute = createRootRoute()
890 const dateRoute = createRoute({
891 getParentRoute: () => rootRoute,
892 path: '/{-$year}/{-$month}/{-$day}',
893 component: () => {
894 const params = dateRoute.useParams()
895 return (
896 <div>
897 <h1>Date Route</h1>
898 <div data-testid="params">{JSON.stringify(params())}</div>
899 </div>
900 )
901 },
902 })
903​
904 window.history.replaceState({}, '', path)
905​
906 const router = createRouter({
907 routeTree: rootRoute.addChildren([dateRoute]),
908 })
909​
910 render(() => <RouterProvider router={router} />)
911 await router.load()
912​
913 const paramsElement = await screen.findByTestId('params')
914 expect(JSON.parse(paramsElement.textContent)).toEqual(expectedParams)
915 },
916 )
917​
918 it.each([
919 {
920 path: '/chambres',
921 expected: {
922 rooms: 'chambres',
923 locale: 'undefined',
924 },
925 },
926 {
927 path: '/fr/chambres',
928 expected: {
929 rooms: 'chambres',
930 locale: 'fr',
931 },
932 },
933 {
934 path: '/rooms',
935 expected: {
936 rooms: 'rooms',
937 locale: 'undefined',
938 },
939 },
940 {
941 path: '/en/rooms',
942 expected: {
943 rooms: 'rooms',
944 locale: 'en',
945 },
946 },
947 ])(
948 'should handle routes with required param after optional param: $path',
949 async ({ path, expected }) => {
950 const rootRoute = createRootRoute()
951 const roomsRoute = createRoute({
952 getParentRoute: () => rootRoute,
953 path: '/{-$locale}/$rooms',
954 component: () => {
955 const params = roomsRoute.useParams()
956 return (
957 <div>
958 <h1>Rooms</h1>
959 <div data-testid="locale-param">
960 {params().locale ?? 'undefined'}
961 </div>
962 <div data-testid="rooms-param">
963 {params().rooms ?? 'undefined'}
964 </div>
965 <Outlet />
966 </div>
967 )
968 },
969 })
970​
971 window.history.replaceState({}, '', path)
972​
973 const router = createRouter({
974 routeTree: rootRoute.addChildren([roomsRoute]),
975 })
976​
977 render(() => <RouterProvider router={router} />)
978 await router.load()
979 const roomsParam = await screen.findByTestId('rooms-param')
980 expect(roomsParam).toHaveTextContent(expected.rooms)
981 const localeParam = await screen.findByTestId('locale-param')
982 expect(localeParam).toHaveTextContent(expected.locale)
983 },
984 )
985 })
986​
987 describe('edge cases and error handling', () => {
988 it('should handle optional parameters with loaders', async () => {
989 const mockLoader = vi.fn((opts) => {
990 return Promise.resolve({
991 category: opts.params.category || 'all',
992 data: `Data for ${opts.params.category || 'all'}`,
993 })
994 })
995​
996 const rootRoute = createRootRoute()
997 const postsRoute = createRoute({
998 getParentRoute: () => rootRoute,
999 path: '/posts/{-$category}',
1000 loader: mockLoader,
1001 component: () => {
1002 const data = postsRoute.useLoaderData()
1003 const params = postsRoute.useParams()
1004 return (
1005 <div>
1006 <h1>Posts</h1>
1007 <div data-testid="params">{JSON.stringify(params())}</div>
1008 <div data-testid="loader-data">{JSON.stringify(data())}</div>
1009 </div>
1011 },
1012 })
1013 window.history.replaceState({}, '', '/posts')
1014​
1015 const router = createRouter({
1016 routeTree: rootRoute.addChildren([postsRoute]),
1017 })
1018​
1019 // Test without category
1020 render(() => <RouterProvider router={router} />)
1021 await router.load()
1022​
1023 await expect(screen.findByText('Posts')).resolves.toBeInTheDocument()
1024 const paramsElement = await screen.findByTestId('params')
1025 const loaderDataElement = await screen.findByTestId('loader-data')
1026​
1027 expect(JSON.parse(paramsElement.textContent)).toEqual({})
1028 expect(JSON.parse(loaderDataElement.textContent)).toEqual({
1029 category: 'all',
1030 data: 'Data for all',
1031 })
1032​
1033 expect(mockLoader).toHaveBeenCalledWith(
1034 expect.objectContaining({
1035 params: {},
1036 }),
1038 })
1039​
1040 it('should handle beforeLoad with optional parameters', async () => {
1041 const mockBeforeLoad = vi.fn((opts) => {
1042 return {
1043 category: opts.params.category || 'default',
1044 timestamp: Date.now(),
1046 })
1047​
1048 const rootRoute = createRootRoute()
1049 const postsRoute = createRoute({
1050 getParentRoute: () => rootRoute,
1051 path: '/posts/{-$category}',
1052 beforeLoad: mockBeforeLoad,
1053 component: () => {
1054 const params = postsRoute.useParams()
1055 return (
1056 <div>
1057 <h1>Posts</h1>
1058 <div data-testid="params">{JSON.stringify(params())}</div>
1059 </div>
1061 },
1062 })
1063 window.history.replaceState({}, '', '/posts/tech')
1064​
1065 const router = createRouter({
1066 routeTree: rootRoute.addChildren([postsRoute]),
1067 })
1068​
1069 render(() => <RouterProvider router={router} />)
1070​
1071 await expect(screen.findByText('Posts')).resolves.toBeInTheDocument()
1072​
1073 expect(mockBeforeLoad).toHaveBeenCalledWith(
1074 expect.objectContaining({
1075 params: { category: 'tech' },
1076 }),
1078 })
1079 })