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

optional-path-params.test.tsx

1,057 lines30.9 KB

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