Open History to see the last commit
1import { afterEach, describe, expect, test } from 'vitest'
2import {
3 act,
4 cleanup,
5 fireEvent,
6 render,
7 renderHook,
8 screen,
9 waitFor,
10} from '@testing-library/react'
11import { createMemoryHistory } from '@tanstack/history'
12import { createControlledPromise } from '@tanstack/router-core'
13import {
14 Link,
15 Outlet,
16 RouterContextProvider,
17 RouterProvider,
18 createRootRoute,
19 createRoute,
20 createRouter,
21 isMatch,
22 useMatchRoute,
23 useMatches,
24} from '../src'
25β
26const rootRoute = createRootRoute()
27β
28const indexRoute = createRoute({
29 getParentRoute: () => rootRoute,
30 path: '/',
31 component: () => {
32 return <Link to="/invoices/">To Invoices</Link>
33 },
34})
35β
36const invoicesRoute = createRoute({
37 getParentRoute: () => rootRoute,
38 path: 'invoices',
39 loader: () => [{ id: '1' }, { id: '2' }],
40 component: () => <Outlet />,
41})
42β
43const InvoicesIndex = () => {
44 const matches = useMatches<DefaultRouter>()
45β
46 const loaderDataMatches = matches.filter((match) =>
47 isMatch(match, 'loaderData.0.id'),
48 )
49β
50 const contextMatches = matches.filter((match) =>
51 isMatch(match, 'context.permissions'),
52 )
53β
54 const incorrectMatches = matches.filter((match) =>
55 isMatch(match, 'loaderData.6.id'),
56 )
57β
58 return (
59 <div>
60 <section>
61 Loader Matches -{' '}
62 {loaderDataMatches.map((match) => match.fullPath).join(',')}
63 </section>
64 <section>
65 Context Matches -{' '}
66 {contextMatches.map((match) => match.fullPath).join(',')}
67 </section>
68 <section>
69 Incorrect Matches -{' '}
70 {incorrectMatches.map((match) => match.fullPath).join(',')}
71 </section>
72 </div>
73 )
74}
75β
76const invoicesIndexRoute = createRoute({
77 getParentRoute: () => invoicesRoute,
78 path: '/',
79 component: InvoicesIndex,
80 context: () => ({
81 permissions: 'permission',
82 }),
83})
84β
85const invoiceRoute = createRoute({
86 getParentRoute: () => invoicesRoute,
87 path: '$invoiceId',
88 validateSearch: () => ({ page: 0 }),
89})
90β
91const layoutRoute = createRoute({
92 getParentRoute: () => rootRoute,
93 id: '_layout',
94})
95β
96const commentsRoute = createRoute({
97 getParentRoute: () => layoutRoute,
98 path: 'comments/$id',
99 validateSearch: () => ({
100 page: 0,
101 search: '',
102 }),
103 loader: () =>
104 [{ comment: 'one comment' }, { comment: 'two comment' }] as const,
105})
106β
107const routeTree = rootRoute.addChildren([
108 invoicesRoute.addChildren([invoicesIndexRoute, invoiceRoute]),
109 indexRoute,
110 layoutRoute.addChildren([commentsRoute]),
111])
112β
113const defaultRouter = createRouter({
114 routeTree,
115})
116β
117type DefaultRouter = typeof defaultRouter
118β
119test('when filtering useMatches by loaderData', async () => {
120 render(<RouterProvider router={defaultRouter} />)
121β
122 const searchLink = await screen.findByRole('link', { name: 'To Invoices' })
123β
124 fireEvent.click(searchLink)
125β
126 expect(
127 await screen.findByText('Loader Matches - /invoices'),
128 ).toBeInTheDocument()
129β
130 expect(
131 await screen.findByText('Context Matches - /invoices/'),
132 ).toBeInTheDocument()
133β
134 expect(await screen.findByText('Incorrect Matches -')).toBeInTheDocument()
135})
136β
137test('should show pendingComponent of root route', async () => {
138 const root = createRootRoute({
139 pendingComponent: () => <div data-testid="root-pending" />,
140 loader: async () => {
141 await new Promise((r) => setTimeout(r, 50))
142 },
143 component: () => <div data-testid="root-content" />,
144 })
145β
146 const router = createRouter({
147 routeTree: root,
148 defaultPendingMs: 0,
149 defaultPendingComponent: () => <div>default pending...</div>,
150 })
151β
152 const rendered = render(<RouterProvider router={router} />)
153β
154 expect(await rendered.findByTestId('root-pending')).toBeInTheDocument()
155 expect(await rendered.findByTestId('root-content')).toBeInTheDocument()
156})
157β
158test('useMatchRoute follows superseding pending locations', async () => {
159 const aGate = createControlledPromise<void>()
160 const bGate = createControlledPromise<void>()
161β
162 function Layout() {
163 const matchRoute = useMatchRoute()
164 return (
165 <div>
166 <span data-testid="pending-a">
167 {String(Boolean(matchRoute({ to: '/a', pending: true })))}
168 </span>
169 <span data-testid="pending-b">
170 {String(Boolean(matchRoute({ to: '/b', pending: true })))}
171 </span>
172 <span data-testid="resolved-b">
173 {String(Boolean(matchRoute({ to: '/b', pending: false })))}
174 </span>
175 <Outlet />
176 </div>
177 )
178 }
179β
180 const root = createRootRoute({ component: Layout })
181 const index = createRoute({
182 getParentRoute: () => root,
183 path: '/',
184 })
185 const a = createRoute({
186 getParentRoute: () => root,
187 path: '/a',
188 loader: () => aGate,
189 })
190 const b = createRoute({
191 getParentRoute: () => root,
192 path: '/b',
193 loader: () => bGate,
194 })
195 const router = createRouter({
196 routeTree: root.addChildren([index, a, b]),
197 history: createMemoryHistory({ initialEntries: ['/'] }),
198 })
199 render(<RouterProvider router={router} />)
200β
201 await waitFor(() => {
202 expect(screen.getByTestId('pending-a')).toHaveTextContent('false')
203 expect(router.stores.status.get()).toBe('idle')
204 expect(router.stores.resolvedLocation.get()?.pathname).toBe('/')
205 })
206β
207 let navigationA!: Promise<void>
208 act(() => {
209 navigationA = router.navigate({ to: '/a' })
210 })
211 await waitFor(() => {
212 expect(screen.getByTestId('pending-a')).toHaveTextContent('true')
213 expect(screen.getByTestId('resolved-b')).toHaveTextContent('false')
214 })
215β
216 let navigationB!: Promise<void>
217 act(() => {
218 navigationB = router.navigate({ to: '/b' })
219 })
220 await waitFor(() => {
221 expect(screen.getByTestId('pending-a')).toHaveTextContent('false')
222 expect(screen.getByTestId('pending-b')).toHaveTextContent('true')
223 expect(screen.getByTestId('resolved-b')).toHaveTextContent('false')
224 })
225β
226 await act(async () => {
227 aGate.resolve()
228 bGate.resolve()
229 await Promise.allSettled([navigationA, navigationB])
230 })
231 await waitFor(() => {
232 expect(screen.getByTestId('pending-b')).toHaveTextContent('false')
233 expect(screen.getByTestId('resolved-b')).toHaveTextContent('true')
234 })
235})
236β
237test('useMatchRoute callback identity tracks route matching state', async () => {
238 const root = createRootRoute()
239 const a = createRoute({
240 getParentRoute: () => root,
241 path: '/a',
242 })
243 const b = createRoute({
244 getParentRoute: () => root,
245 path: '/b',
246 })
247 const router = createRouter({
248 routeTree: root.addChildren([a, b]),
249 history: createMemoryHistory({ initialEntries: ['/'] }),
250 })
251 const aLocation = router.buildLocation({ to: '/a' })
252 const bLocation = router.buildLocation({ to: '/b' })
253β
254 const { result, rerender } = renderHook(() => useMatchRoute(), {
255 wrapper: ({ children }) => (
256 <RouterContextProvider router={router}>{children}</RouterContextProvider>
257 ),
258 })
259β
260 let previous = result.current
261 rerender()
262 expect(result.current).toBe(previous)
263β
264 async function expectCallbackInvalidated(update: () => void) {
265 previous = result.current
266 act(update)
267 await waitFor(() => expect(result.current).not.toBe(previous))
268 }
269β
270 await expectCallbackInvalidated(() => {
271 router.stores.location.set(aLocation)
272 })
273 await expectCallbackInvalidated(() => {
274 router.stores.resolvedLocation.set(bLocation)
275 })
276 await expectCallbackInvalidated(() => {
277 router.stores.status.set('pending')
278 })
279β
280 previous = result.current
281 act(() => {
282 router.stores.location.set({ ...aLocation })
283 router.stores.resolvedLocation.set({ ...bLocation })
284 router.stores.status.set('pending')
285 })
286 rerender()
287 expect(result.current).toBe(previous)
288})
289β
290test('legacy notFoundRoute drops a stale parent layout after navigation', async () => {
291 let legacyLoads = 0
292 const root = createRootRoute({ component: Outlet })
293 const parent = createRoute({
294 getParentRoute: () => root,
295 path: '/parent',
296 component: () => (
297 <div>
298 Parent layout
299 <Outlet />
300 </div>
301 ),
302 })
303 const known = createRoute({
304 getParentRoute: () => parent,
305 path: '/known',
306 })
307 const legacyNotFound = createRoute({
308 getParentRoute: () => root,
309 path: '/404',
310 loader: () => {
311 legacyLoads++
312 return 'not found'
313 },
314 component: () => <div>Legacy not found</div>,
315 staleTime: Infinity,
316 gcTime: Infinity,
317 })
318 const router = createRouter({
319 routeTree: root.addChildren([parent.addChildren([known])]),
320 history: createMemoryHistory({ initialEntries: ['/parent/missing'] }),
321 notFoundRoute: legacyNotFound,
322 })
323β
324 const rendered = render(<RouterProvider router={router} />)
325 expect(await rendered.findByText('Parent layout')).toBeInTheDocument()
326 expect(await rendered.findByText('Legacy not found')).toBeInTheDocument()
327 expect(legacyLoads).toBe(1)
328β
329 await act(async () => {
330 await router.navigate({ to: '/missing' } as any)
331 })
332β
333 expect(rendered.queryByText('Parent layout')).not.toBeInTheDocument()
334 expect(await rendered.findByText('Legacy not found')).toBeInTheDocument()
335 expect(legacyLoads).toBe(1)
336 rendered.unmount()
337})
338β
339describe('matching on different param types', () => {
340 const testCases = [
341 {
342 name: 'param with braces',
343 path: '/$id',
344 nav: '/1',
345 params: { id: '1' },
346 matchParams: { id: '1' },
347 },
348 {
349 name: 'param without braces',
350 path: '/{$id}',
351 nav: '/2',
352 params: { id: '2' },
353 matchParams: { id: '2' },
354 },
355 {
356 name: 'param with prefix',
357 path: '/prefix-{$id}',
358 nav: '/prefix-3',
359 params: { id: '3' },
360 matchParams: { id: '3' },
361 },
362 {
363 name: 'param with suffix',
364 path: '/{$id}-suffix',
365 nav: '/4-suffix',
366 params: { id: '4' },
367 matchParams: { id: '4' },
368 },
369 {
370 name: 'param with prefix and suffix',
371 path: '/prefix-{$id}-suffix',
372 nav: '/prefix-5-suffix',
373 params: { id: '5' },
374 matchParams: { id: '5' },
375 },
376 {
377 name: 'wildcard with no braces',
378 path: '/abc/$',
379 nav: '/abc/6',
380 params: { '*': '6', _splat: '6' },
381 matchParams: { '*': '6', _splat: '6' },
382 },
383 {
384 name: 'wildcard with braces',
385 path: '/abc/{$}',
386 nav: '/abc/7',
387 params: { '*': '7', _splat: '7' },
388 matchParams: { '*': '7', _splat: '7' },
389 },
390 {
391 name: 'wildcard with prefix',
392 path: '/abc/prefix{$}',
393 nav: '/abc/prefix/8',
394 params: { '*': '/8', _splat: '/8' },
395 matchParams: { '*': '/8', _splat: '/8' },
396 },
397 {
398 name: 'wildcard with suffix',
399 path: '/abc/{$}suffix',
400 nav: '/abc/9/suffix',
401 params: { _splat: '9/', '*': '9/' },
402 matchParams: { _splat: '9/', '*': '9/' },
403 },
404 {
405 name: 'optional param with no prefix/suffix and value',
406 path: '/abc/{-$id}/def',
407 nav: '/abc/10/def',
408 params: { id: '10' },
409 matchParams: { id: '10' },
410 },
411 {
412 name: 'optional param with no prefix/suffix and requiredParam and no value',
413 path: '/abc/{-$id}/$foo/def',
414 nav: '/abc/bar/def',
415 params: { foo: 'bar' },
416 matchParams: { foo: 'bar' },
417 },
418 {
419 name: 'optional param with no prefix/suffix and requiredParam and value',
420 path: '/abc/{-$id}/$foo/def',
421 nav: '/abc/10/bar/def',
422 params: { id: '10', foo: 'bar' },
423 matchParams: { id: '10', foo: 'bar' },
424 },
425 {
426 name: 'optional param with no prefix/suffix and no value',
427 path: '/abc/{-$id}/def',
428 nav: '/abc/def',
429 params: {},
430 matchParams: {},
431 },
432 {
433 name: 'multiple optional params with no prefix/suffix and no value',
434 path: '/{-$a}/{-$b}/{-$c}',
435 nav: '/',
436 params: {},
437 matchParams: {},
438 },
439 {
440 name: 'multiple optional params with no prefix/suffix and values',
441 path: '/{-$a}/{-$b}/{-$c}',
442 nav: '/foo/bar/qux',
443 params: { a: 'foo', b: 'bar', c: 'qux' },
444 matchParams: { a: 'foo', b: 'bar', c: 'qux' },
445 },
446 {
447 name: 'multiple optional params with no prefix/suffix and mixed values',
448 path: '/{-$a}/{-$b}/{-$c}',
449 nav: '/foo/qux',
450 params: { a: 'foo', b: 'qux' },
451 matchParams: { a: 'foo', b: 'qux' },
452 },
453 {
454 name: 'optional param with prefix and value',
455 path: '/optional-{-$id}',
456 nav: '/optional-12',
457 params: { id: '12' },
458 matchParams: { id: '12' },
459 },
460 {
461 name: 'optional param with prefix and no value',
462 path: '/optional-{-$id}',
463 nav: '/optional-',
464 params: {},
465 matchParams: {},
466 },
467 {
468 name: 'optional param with suffix and value',
469 path: '/{-$id}-optional',
470 nav: '/13-optional',
471 params: { id: '13' },
472 matchParams: { id: '13' },
473 },
474 {
475 name: 'optional param with suffix and no value',
476 path: '/{-$id}-optional',
477 nav: '/-optional',
478 params: {},
479 matchParams: {},
480 },
481 {
482 name: 'optional param with required param, prefix, suffix, wildcard and no value',
483 path: `/$foo/a{-$id}-optional/$`,
484 nav: '/bar/a-optional/qux',
485 params: { foo: 'bar', _splat: 'qux', '*': 'qux' },
486 matchParams: { foo: 'bar', _splat: 'qux', '*': 'qux' },
487 },
488 {
489 name: 'optional param with required param, prefix, suffix, wildcard and value',
490 path: `/$foo/a{-$id}-optional/$`,
491 nav: '/bar/a14-optional/qux',
492 params: { foo: 'bar', id: '14', _splat: 'qux', '*': 'qux' },
493 matchParams: { foo: 'bar', id: '14', _splat: 'qux', '*': 'qux' },
494 },
495 ]
496β
497 afterEach(() => cleanup())
498 test.each(testCases)(
499 '$name',
500 async ({ name, path, params, matchParams, nav }) => {
501 const rootRoute = createRootRoute()
502β
503 const Route = createRoute({
504 getParentRoute: () => rootRoute,
505 path,
506 component: RouteComponent,
507 })
508β
509 function RouteComponent() {
510 const routeParams = Route.useParams()
511 const matchRoute = useMatchRoute()
512 const matchRouteMatch = matchRoute({
513 to: path,
514 })
515β
516 return (
517 <div>
518 <h1 data-testid="heading">{name}</h1>
519 <div>
520 Params{' '}
521 <span data-testid="params">{JSON.stringify(routeParams)}</span>
522 Matches{' '}
523 <span data-testid="matches">
524 {JSON.stringify(matchRouteMatch)}
525 </span>
526 </div>
527 </div>
528 )
529 }
530β
531 const router = createRouter({
532 routeTree: rootRoute.addChildren([Route]),
533 history: createMemoryHistory({ initialEntries: ['/'] }),
534 })
535β
536 await act(() => render(<RouterProvider router={router} />))
537β
538 act(() => router.history.push(nav))
539β
540 const paramsToCheck = await screen.findByTestId('params')
541 const matchesToCheck = await screen.findByTestId('matches')
542β
543 expect(JSON.parse(paramsToCheck.textContent)).toEqual(params)
544 expect(JSON.parse(matchesToCheck.textContent)).toEqual(matchParams)
545 },
546 )
547})