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

Matches.test.tsx

514 lines13.9 KB

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