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

optional-path-params.test.tsx

1,069 lines31.0 KB

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