-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathrouter.test.tsx
More file actions
612 lines (497 loc) 路 16.5 KB
/
Copy pathrouter.test.tsx
File metadata and controls
612 lines (497 loc) 路 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
import { act, useEffect } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
cleanup,
fireEvent,
render,
screen,
waitFor,
} from '@testing-library/react'
import { z } from 'zod'
import {
Link,
Outlet,
RouterProvider,
createMemoryHistory,
createRootRoute,
createRoute,
createRouter,
} from '../src'
import type { RouterHistory } from '../src'
afterEach(() => {
vi.resetAllMocks()
window.history.replaceState(null, 'root', '/')
cleanup()
})
const mockFn1 = vi.fn()
function createTestRouter(initialHistory?: RouterHistory) {
let history
if (initialHistory) {
history = initialHistory
}
const rootRoute = createRootRoute({})
const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/' })
const postsRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/posts',
})
const postIdRoute = createRoute({
getParentRoute: () => postsRoute,
path: '/$slug',
})
const topLevelSplatRoute = createRoute({
getParentRoute: () => rootRoute,
path: '$',
})
// This is simulates a user creating a `茅.tsx` file using file-based routing
const pathSegmentEAccentRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/path-segment/茅',
})
// This is simulates a user creating a `馃殌.tsx` file using file-based routing
const pathSegmentRocketEmojiRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/path-segment/馃殌',
})
const pathSegmentSoloSplatRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/solo-splat/$',
})
const pathSegmentLayoutSplatRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/layout-splat',
})
const pathSegmentLayoutSplatIndexRoute = createRoute({
getParentRoute: () => pathSegmentLayoutSplatRoute,
path: '/',
})
const pathSegmentLayoutSplatSplatRoute = createRoute({
getParentRoute: () => pathSegmentLayoutSplatRoute,
path: '$',
})
const routeWithParamsParseStringify = createRoute({
getParentRoute: () => rootRoute,
path: '/paramsParseStringify/$id',
params: {
parse: (params) => ({
id: z.number().int().parse(Number(params.id)),
}),
stringify: ({ id }) => ({ id: `${id}` }),
},
})
const routeTree = rootRoute.addChildren([
indexRoute,
postsRoute.addChildren([postIdRoute]),
pathSegmentEAccentRoute,
pathSegmentRocketEmojiRoute,
pathSegmentSoloSplatRoute,
topLevelSplatRoute,
pathSegmentLayoutSplatRoute.addChildren([
pathSegmentLayoutSplatIndexRoute,
pathSegmentLayoutSplatSplatRoute,
]),
routeWithParamsParseStringify,
])
const router = createRouter({ routeTree, history })
return {
router,
routes: {
indexRoute,
postsRoute,
postIdRoute,
topLevelSplatRoute,
pathSegmentEAccentRoute,
pathSegmentRocketEmojiRoute,
},
}
}
describe('encoding: URL param segment for /posts/$slug', () => {
it('state.location.pathname, should have the params.slug value of "tanner"', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/posts/tanner'] }),
)
await act(() => router.load())
expect(router.state.location.pathname).toBe('/posts/tanner')
})
it('state.location.pathname, should have the params.slug value of "馃殌"', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/posts/馃殌'] }),
)
await act(() => router.load())
expect(router.state.location.pathname).toBe('/posts/馃殌')
})
it('state.location.pathname, should have the params.slug value of "%F0%9F%9A%80"', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/posts/%F0%9F%9A%80'] }),
)
await act(() => router.load())
expect(router.state.location.pathname).toBe('/posts/%F0%9F%9A%80')
})
it('state.location.pathname, should have the params.slug value of "framework%2Freact%2Fguide%2Ffile-based-routing%20tanstack"', async () => {
const { router } = createTestRouter(
createMemoryHistory({
initialEntries: [
'/posts/framework%2Freact%2Fguide%2Ffile-based-routing%20tanstack',
],
}),
)
await act(() => router.load())
expect(router.state.location.pathname).toBe(
'/posts/framework%2Freact%2Fguide%2Ffile-based-routing%20tanstack',
)
})
it('params.slug for the matched route, should be "tanner"', async () => {
const { router, routes } = createTestRouter(
createMemoryHistory({ initialEntries: ['/posts/tanner'] }),
)
await act(() => router.load())
const match = router.state.matches.find(
(r) => r.routeId === routes.postIdRoute.id,
)
if (!match) {
throw new Error('No match found')
}
expect((match.params as unknown as any).slug).toBe('tanner')
})
it('params.slug for the matched route, should be "馃殌"', async () => {
const { router, routes } = createTestRouter(
createMemoryHistory({ initialEntries: ['/posts/馃殌'] }),
)
await act(() => router.load())
const match = router.state.matches.find(
(r) => r.routeId === routes.postIdRoute.id,
)
if (!match) {
throw new Error('No match found')
}
expect((match.params as unknown as any).slug).toBe('馃殌')
})
it('params.slug for the matched route, should be "馃殌" instead of it being "%F0%9F%9A%80"', async () => {
const { router, routes } = createTestRouter(
createMemoryHistory({ initialEntries: ['/posts/%F0%9F%9A%80'] }),
)
await act(() => router.load())
const match = router.state.matches.find(
(r) => r.routeId === routes.postIdRoute.id,
)
if (!match) {
throw new Error('No match found')
}
expect((match.params as unknown as any).slug).toBe('馃殌')
})
it('params.slug for the matched route, should be "framework/react/guide/file-based-routing tanstack" instead of it being "framework%2Freact%2Fguide%2Ffile-based-routing%20tanstack"', async () => {
const { router, routes } = createTestRouter(
createMemoryHistory({
initialEntries: [
'/posts/framework%2Freact%2Fguide%2Ffile-based-routing%20tanstack',
],
}),
)
await act(() => router.load())
const match = router.state.matches.find(
(r) => r.routeId === routes.postIdRoute.id,
)
if (!match) {
throw new Error('No match found')
}
expect((match.params as unknown as any).slug).toBe(
'framework/react/guide/file-based-routing tanstack',
)
})
})
describe('encoding: URL splat segment for /$', () => {
it('state.location.pathname, should have the params._splat value of "tanner"', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/tanner'] }),
)
await router.load()
expect(router.state.location.pathname).toBe('/tanner')
})
it('state.location.pathname, should have the params._splat value of "馃殌"', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/馃殌'] }),
)
await router.load()
expect(router.state.location.pathname).toBe('/馃殌')
})
it('state.location.pathname, should have the params._splat value of "%F0%9F%9A%80"', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/%F0%9F%9A%80'] }),
)
await router.load()
expect(router.state.location.pathname).toBe('/%F0%9F%9A%80')
})
it('state.location.pathname, should have the params._splat value of "framework%2Freact%2Fguide%2Ffile-based-routing%20tanstack"', async () => {
const { router } = createTestRouter(
createMemoryHistory({
initialEntries: [
'/framework%2Freact%2Fguide%2Ffile-based-routing%20tanstack',
],
}),
)
await router.load()
expect(router.state.location.pathname).toBe(
'/framework%2Freact%2Fguide%2Ffile-based-routing%20tanstack',
)
})
it('state.location.pathname, should have the params._splat value of "framework/react/guide/file-based-routing tanstack"', async () => {
const { router } = createTestRouter(
createMemoryHistory({
initialEntries: ['/framework/react/guide/file-based-routing tanstack'],
}),
)
await router.load()
expect(router.state.location.pathname).toBe(
'/framework/react/guide/file-based-routing tanstack',
)
})
it('params._splat for the matched route, should be "tanner"', async () => {
const { router, routes } = createTestRouter(
createMemoryHistory({ initialEntries: ['/tanner'] }),
)
await router.load()
const match = router.state.matches.find(
(r) => r.routeId === routes.topLevelSplatRoute.id,
)
if (!match) {
throw new Error('No match found')
}
expect((match.params as unknown as any)._splat).toBe('tanner')
})
it('params._splat for the matched route, should be "馃殌"', async () => {
const { router, routes } = createTestRouter(
createMemoryHistory({ initialEntries: ['/馃殌'] }),
)
await router.load()
const match = router.state.matches.find(
(r) => r.routeId === routes.topLevelSplatRoute.id,
)
if (!match) {
throw new Error('No match found')
}
expect((match.params as unknown as any)._splat).toBe('馃殌')
})
it('params._splat for the matched route, should be "馃殌" instead of it being "%F0%9F%9A%80"', async () => {
const { router, routes } = createTestRouter(
createMemoryHistory({ initialEntries: ['/%F0%9F%9A%80'] }),
)
await router.load()
const match = router.state.matches.find(
(r) => r.routeId === routes.topLevelSplatRoute.id,
)
if (!match) {
throw new Error('No match found')
}
expect((match.params as unknown as any)._splat).toBe('馃殌')
})
it('params._splat for the matched route, should be "framework/react/guide/file-based-routing tanstack"', async () => {
const { router, routes } = createTestRouter(
createMemoryHistory({
initialEntries: ['/framework/react/guide/file-based-routing tanstack'],
}),
)
await router.load()
const match = router.state.matches.find(
(r) => r.routeId === routes.topLevelSplatRoute.id,
)
if (!match) {
throw new Error('No match found')
}
expect((match.params as unknown as any)._splat).toBe(
'framework/react/guide/file-based-routing tanstack',
)
})
})
describe('encoding: URL path segment', () => {
it.each([
{
input: '/path-segment/%C3%A9',
output: '/path-segment/茅',
type: 'encoded',
},
{
input: '/path-segment/茅',
output: '/path-segment/茅',
type: 'not encoded',
},
{
input: '/path-segment/%F0%9F%9A%80',
output: '/path-segment/馃殌',
type: 'encoded',
},
{
input: '/path-segment/%F0%9F%9A%80to%2Fthe%2Fmoon',
output: '/path-segment/馃殌to%2Fthe%2Fmoon',
type: 'encoded',
},
{
input: '/path-segment/馃殌',
output: '/path-segment/馃殌',
type: 'not encoded',
},
{
input: '/path-segment/馃殌to%2Fthe%2Fmoon',
output: '/path-segment/馃殌to%2Fthe%2Fmoon',
type: 'not encoded',
},
])(
'should resolve $input to $output when the path segment is $type',
async ({ input, output }) => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: [input] }),
)
render(<RouterProvider router={router} />)
await act(() => router.load())
expect(router.state.location.pathname).toBe(output)
},
)
})
describe('router emits events during rendering', () => {
it('during initial load, should emit the "onResolved" event', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/'] }),
)
const unsub = router.subscribe('onResolved', mockFn1)
await router.load()
render(<RouterProvider router={router} />)
await waitFor(() => expect(mockFn1).toBeCalled())
unsub()
})
it('after a navigation, should have emitted the "onResolved" event twice', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/'] }),
)
const unsub = router.subscribe('onResolved', mockFn1)
await router.load()
render(<RouterProvider router={router} />)
await act(() => router.navigate({ to: '/$', params: { _splat: 'tanner' } }))
await waitFor(() => expect(mockFn1).toBeCalledTimes(2))
unsub()
})
})
describe('router rendering stability', () => {
it('should not remount the page component when navigating to the same route', async () => {
const callerMock = vi.fn()
const rootRoute = createRootRoute({
component: () => {
return (
<div>
<p>Root</p>
<div>
<Link to="/foo/$id" params={{ id: '1' }}>
Foo1
</Link>
<Link to="/foo/$id" params={{ id: '2' }}>
Foo2
</Link>
</div>
<Outlet />
</div>
)
},
})
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
component: () => {
return ''
},
})
const fooIdRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/foo/$id',
component: FooIdRouteComponent,
})
function FooIdRouteComponent() {
const id = fooIdRoute.useParams({ select: (s) => s.id })
useEffect(() => {
callerMock()
}, [])
return <div>Foo page {id}</div>
}
const routeTree = rootRoute.addChildren([fooIdRoute, indexRoute])
const router = createRouter({ routeTree })
render(<RouterProvider router={router} />)
const foo1Link = await screen.findByRole('link', { name: 'Foo1' })
const foo2Link = await screen.findByRole('link', { name: 'Foo2' })
expect(foo1Link).toBeInTheDocument()
expect(foo2Link).toBeInTheDocument()
fireEvent.click(foo1Link)
const fooPage1 = await screen.findByText('Foo page 1')
expect(fooPage1).toBeInTheDocument()
expect(callerMock).toBeCalledTimes(1)
fireEvent.click(foo2Link)
const fooPage2 = await screen.findByText('Foo page 2')
expect(fooPage2).toBeInTheDocument()
expect(callerMock).toBeCalledTimes(1)
})
})
describe('transformer functions are defined', () => {
it('should have default transformer functions', () => {
const rootRoute = createRootRoute({})
const routeTree = rootRoute.addChildren([])
const router = createRouter({ routeTree })
expect(router.options.transformer.parse).toBeInstanceOf(Function)
expect(router.options.transformer.stringify).toBeInstanceOf(Function)
})
})
describe('router matches URLs to route definitions', () => {
it('solo splat route matches index route', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/solo-splat'] }),
)
await act(() => router.load())
expect(router.state.matches.map((d) => d.routeId)).toEqual([
'__root__',
'/solo-splat/$',
])
})
it('solo splat route matches with splat', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/solo-splat/test'] }),
)
await act(() => router.load())
expect(router.state.matches.map((d) => d.routeId)).toEqual([
'__root__',
'/solo-splat/$',
])
})
it('layout splat route matches with splat', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/layout-splat/test'] }),
)
await act(() => router.load())
expect(router.state.matches.map((d) => d.routeId)).toEqual([
'__root__',
'/layout-splat',
'/layout-splat/$',
])
})
it('layout splat route matches without splat', async () => {
const { router } = createTestRouter(
createMemoryHistory({ initialEntries: ['/layout-splat'] }),
)
await act(() => router.load())
expect(router.state.matches.map((d) => d.routeId)).toEqual([
'__root__',
'/layout-splat',
'/layout-splat/',
])
})
})
describe('matchRoute', () => {
it('should match route with custom parse/stringify functions', async () => {
const { router } = createTestRouter(
createMemoryHistory({
initialEntries: ['/paramsParseStringify/123'],
}),
)
await act(() => router.load())
const result = router.matchRoute({
to: '/paramsParseStringify/$id',
params: { id: 123 },
})
expect(result).toBeTruthy()
expect((result as any).id).toBe(123)
})
})