Open History to see the last commit
1import React from 'react'
2import '@testing-library/jest-dom/vitest'
3import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
4import { cleanup, fireEvent, render, screen } from '@testing-library/react'
5β
6import { z } from 'zod'
7import {
8 RouterProvider,
9 createBrowserHistory,
10 createMemoryHistory,
11 createRootRoute,
12 createRoute,
13 createRouter,
14 useBlocker,
15 useNavigate,
16} from '../src'
17import type { RouterHistory } from '../src'
18β
19let history: RouterHistory
20β
21beforeEach(() => {
22 history = createBrowserHistory()
23 expect(window.location.pathname).toBe('/')
24})
25β
26afterEach(() => {
27 history.destroy()
28 window.history.replaceState(null, 'root', '/')
29 vi.clearAllMocks()
30 vi.resetAllMocks()
31 cleanup()
32})
33β
34describe('useBlocker', () => {
35 test('does not block navigation when not enabled', async () => {
36 const rootRoute = createRootRoute()
37β
38 const IndexComponent = () => {
39 const navigate = useNavigate()
40β
41 useBlocker({ shouldBlockFn: () => false })
42β
43 return (
44 <>
45 <h1>Index</h1>
46 <button onClick={() => navigate({ to: '/' })}>Index</button>
47 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
48 </>
49 )
50 }
51β
52 const indexRoute = createRoute({
53 getParentRoute: () => rootRoute,
54 path: '/',
55 component: IndexComponent,
56 })
57β
58 const postsRoute = createRoute({
59 getParentRoute: () => rootRoute,
60 path: '/posts',
61 component: () => {
62 return (
63 <>
64 <h1>Posts</h1>
65 </>
66 )
67 },
68 })
69β
70 const router = createRouter({
71 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
72 history,
73 })
74β
75 render(<RouterProvider router={router} />)
76β
77 const postsButton = await screen.findByRole('button', { name: 'Posts' })
78β
79 fireEvent.click(postsButton)
80β
81 expect(
82 await screen.findByRole('heading', { name: 'Posts' }),
83 ).toBeInTheDocument()
84β
85 expect(window.location.pathname).toBe('/posts')
86 })
87β
88 test('does not block navigation when disabled', async () => {
89 const rootRoute = createRootRoute()
90β
91 const IndexComponent = () => {
92 const navigate = useNavigate()
93β
94 useBlocker({ shouldBlockFn: () => true, disabled: true })
95β
96 return (
97 <>
98 <h1>Index</h1>
99 <button onClick={() => navigate({ to: '/' })}>Index</button>
100 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
101 </>
102 )
103 }
104β
105 const indexRoute = createRoute({
106 getParentRoute: () => rootRoute,
107 path: '/',
108 component: IndexComponent,
109 })
110β
111 const postsRoute = createRoute({
112 getParentRoute: () => rootRoute,
113 path: '/posts',
114 component: () => {
115 return (
116 <>
117 <h1>Posts</h1>
118 </>
119 )
120 },
121 })
122β
123 const router = createRouter({
124 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
125 history,
126 })
127β
128 render(<RouterProvider router={router} />)
129β
130 const postsButton = await screen.findByRole('button', { name: 'Posts' })
131β
132 fireEvent.click(postsButton)
133β
134 expect(
135 await screen.findByRole('heading', { name: 'Posts' }),
136 ).toBeInTheDocument()
137β
138 expect(window.location.pathname).toBe('/posts')
139 })
140β
141 test('blocks navigation when enabled', async () => {
142 const rootRoute = createRootRoute()
143β
144 const IndexComponent = () => {
145 const navigate = useNavigate()
146β
147 useBlocker({ shouldBlockFn: () => true })
148β
149 return (
150 <>
151 <h1>Index</h1>
152 <button onClick={() => navigate({ to: '/' })}>Index</button>
153 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
154 </>
155 )
156 }
157β
158 const indexRoute = createRoute({
159 getParentRoute: () => rootRoute,
160 path: '/',
161 component: IndexComponent,
162 })
163β
164 const postsRoute = createRoute({
165 getParentRoute: () => rootRoute,
166 path: '/posts',
167 component: () => {
168 return (
169 <>
170 <h1>Posts</h1>
171 </>
172 )
173 },
174 })
175β
176 const router = createRouter({
177 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
178 history,
179 })
180β
181 render(<RouterProvider router={router} />)
182β
183 const postsButton = await screen.findByRole('button', { name: 'Posts' })
184β
185 fireEvent.click(postsButton)
186β
187 expect(
188 await screen.findByRole('heading', { name: 'Index' }),
189 ).toBeInTheDocument()
190β
191 expect(window.location.pathname).toBe('/')
192 })
193β
194 test('gives correct arguments to shouldBlockFn', async () => {
195 const rootRoute = createRootRoute()
196β
197 const shouldBlockFn = vi.fn().mockReturnValue(true)
198β
199 const IndexComponent = () => {
200 const navigate = useNavigate()
201β
202 useBlocker({ shouldBlockFn })
203β
204 return (
205 <>
206 <h1>Index</h1>
207 <button onClick={() => navigate({ to: '/' })}>Index</button>
208 <button onClick={() => navigate({ to: '/posts', replace: true })}>
209 Posts
210 </button>
211 </>
212 )
213 }
214β
215 const indexRoute = createRoute({
216 getParentRoute: () => rootRoute,
217 path: '/',
218 component: IndexComponent,
219 })
220β
221 const postsRoute = createRoute({
222 getParentRoute: () => rootRoute,
223 path: '/posts',
224 component: () => {
225 return (
226 <>
227 <h1>Posts</h1>
228 </>
229 )
230 },
231 })
232β
233 const router = createRouter({
234 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
235 history,
236 })
237β
238 render(<RouterProvider router={router} />)
239β
240 const postsButton = await screen.findByRole('button', { name: 'Posts' })
241β
242 fireEvent.click(postsButton)
243β
244 expect(
245 await screen.findByRole('heading', { name: 'Index' }),
246 ).toBeInTheDocument()
247β
248 expect(window.location.pathname).toBe('/')
249β
250 expect(shouldBlockFn).toHaveBeenCalledWith({
251 action: 'REPLACE',
252 current: {
253 routeId: indexRoute.id,
254 fullPath: indexRoute.fullPath,
255 pathname: '/',
256 params: {},
257 search: {},
258 },
259 next: {
260 routeId: postsRoute.id,
261 fullPath: postsRoute.fullPath,
262 pathname: '/posts',
263 params: {},
264 search: {},
265 },
266 })
267 })
268β
269 test('gives correct arguments to shouldBlockFn with path and search params', async () => {
270 const rootRoute = createRootRoute()
271β
272 const shouldBlockFn = vi.fn().mockReturnValue(true)
273β
274 const IndexComponent = () => {
275 const navigate = useNavigate()
276β
277 useBlocker({ shouldBlockFn })
278β
279 return (
280 <>
281 <h1>Index</h1>
282 <button onClick={() => navigate({ to: '/' })}>Index</button>
283 <button
284 onClick={() =>
285 navigate({
286 to: '/posts/$postId',
287 params: { postId: '10' },
288 search: { param1: 'foo', param2: 'bar' },
289 })
290 }
291 >
292 Posts
293 </button>
294 </>
295 )
296 }
297β
298 const indexRoute = createRoute({
299 getParentRoute: () => rootRoute,
300 path: '/',
301 component: IndexComponent,
302 })
303β
304 const postsRoute = createRoute({
305 getParentRoute: () => rootRoute,
306 validateSearch: z.object({
307 param1: z.string().default('param1-default'),
308 param2: z.string().default('param2-default'),
309 }),
310 path: '/posts/$postId',
311 component: () => {
312 return (
313 <>
314 <h1>Posts</h1>
315 </>
316 )
317 },
318 })
319β
320 const router = createRouter({
321 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
322 history,
323 })
324β
325 render(<RouterProvider router={router} />)
326β
327 const postsButton = await screen.findByRole('button', { name: 'Posts' })
328β
329 fireEvent.click(postsButton)
330β
331 expect(
332 await screen.findByRole('heading', { name: 'Index' }),
333 ).toBeInTheDocument()
334β
335 expect(window.location.pathname).toBe('/')
336β
337 expect(shouldBlockFn).toHaveBeenCalledWith({
338 action: 'PUSH',
339 current: {
340 routeId: indexRoute.id,
341 fullPath: indexRoute.fullPath,
342 pathname: '/',
343 params: {},
344 search: {},
345 },
346 next: {
347 routeId: postsRoute.id,
348 fullPath: postsRoute.fullPath,
349 pathname: '/posts/10',
350 params: { postId: '10' },
351 search: { param1: 'foo', param2: 'bar' },
352 },
353 })
354 })
355β
356 test('conditionally blocking navigation works', async () => {
357 const rootRoute = createRootRoute()
358β
359 const IndexComponent = () => {
360 const navigate = useNavigate()
361β
362 useBlocker<Router>({
363 shouldBlockFn: ({ next }) => {
364 if (next.fullPath === '/posts') {
365 return true
366 }
367 return false
368 },
369 })
370β
371 return (
372 <>
373 <h1>Index</h1>
374 <button onClick={() => navigate({ to: '/' })}>Index</button>
375 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
376 <button onClick={() => navigate({ to: '/invoices' })}>
377 Invoices
378 </button>
379 </>
380 )
381 }
382β
383 const indexRoute = createRoute({
384 getParentRoute: () => rootRoute,
385 path: '/',
386 component: IndexComponent,
387 })
388β
389 const postsRoute = createRoute({
390 getParentRoute: () => rootRoute,
391 path: '/posts',
392 component: () => {
393 return (
394 <>
395 <h1>Posts</h1>
396 </>
397 )
398 },
399 })
400β
401 const invoicesRoute = createRoute({
402 getParentRoute: () => rootRoute,
403 path: '/invoices',
404 component: () => {
405 return (
406 <>
407 <h1>Invoices</h1>
408 </>
409 )
410 },
411 })
412β
413 const router = createRouter({
414 routeTree: rootRoute.addChildren([indexRoute, postsRoute, invoicesRoute]),
415 history,
416 })
417β
418 type Router = typeof router
419β
420 render(<RouterProvider router={router} />)
421β
422 const postsButton = await screen.findByRole('button', { name: 'Posts' })
423β
424 fireEvent.click(postsButton)
425β
426 expect(
427 await screen.findByRole('heading', { name: 'Index' }),
428 ).toBeInTheDocument()
429β
430 expect(window.location.pathname).toBe('/')
431β
432 const invoicesButton = await screen.findByRole('button', {
433 name: 'Invoices',
434 })
435β
436 fireEvent.click(invoicesButton)
437β
438 expect(
439 await screen.findByRole('heading', { name: 'Invoices' }),
440 ).toBeInTheDocument()
441β
442 expect(window.location.pathname).toBe('/invoices')
443 })
444β
445 test('should allow navigation from 404 page when blocker is active', async () => {
446 const rootRoute = createRootRoute({
447 notFoundComponent: function NotFoundComponent() {
448 const navigate = useNavigate()
449β
450 useBlocker({ shouldBlockFn: () => true })
451β
452 return (
453 <>
454 <h1>Not Found</h1>
455 <button onClick={() => navigate({ to: '/' })}>Go Home</button>
456 <button onClick={() => navigate({ to: '/posts' })}>
457 Go to Posts
458 </button>
459 </>
460 )
461 },
462 })
463β
464 const indexRoute = createRoute({
465 getParentRoute: () => rootRoute,
466 path: '/',
467 component: () => {
468 return (
469 <>
470 <h1>Index</h1>
471 </>
472 )
473 },
474 })
475β
476 const postsRoute = createRoute({
477 getParentRoute: () => rootRoute,
478 path: '/posts',
479 component: () => {
480 return (
481 <>
482 <h1>Posts</h1>
483 </>
484 )
485 },
486 })
487β
488 const router = createRouter({
489 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
490 history,
491 })
492β
493 render(<RouterProvider router={router} />)
494β
495 await router.navigate({ to: '/non-existent' as any })
496β
497 expect(
498 await screen.findByRole('heading', { name: 'Not Found' }),
499 ).toBeInTheDocument()
500β
501 expect(window.location.pathname).toBe('/non-existent')
502β
503 const homeButton = await screen.findByRole('button', { name: 'Go Home' })
504 fireEvent.click(homeButton)
505β
506 expect(
507 await screen.findByRole('heading', { name: 'Index' }),
508 ).toBeInTheDocument()
509β
510 expect(window.location.pathname).toBe('/')
511 })
512β
513 test('should handle blocker navigation from 404 to another 404', async () => {
514 const rootRoute = createRootRoute({
515 notFoundComponent: function NotFoundComponent() {
516 const navigate = useNavigate()
517β
518 useBlocker({ shouldBlockFn: () => true })
519β
520 return (
521 <>
522 <h1>Not Found</h1>
523 <button onClick={() => navigate({ to: '/another-404' as any })}>
524 Go to Another 404
525 </button>
526 </>
527 )
528 },
529 })
530β
531 const indexRoute = createRoute({
532 getParentRoute: () => rootRoute,
533 path: '/',
534 component: () => {
535 return (
536 <>
537 <h1>Index</h1>
538 </>
539 )
540 },
541 })
542β
543 const router = createRouter({
544 routeTree: rootRoute.addChildren([indexRoute]),
545 history,
546 })
547β
548 render(<RouterProvider router={router} />)
549β
550 await router.navigate({ to: '/non-existent' })
551β
552 expect(
553 await screen.findByRole('heading', { name: 'Not Found' }),
554 ).toBeInTheDocument()
555β
556 const anotherButton = await screen.findByRole('button', {
557 name: 'Go to Another 404',
558 })
559 fireEvent.click(anotherButton)
560β
561 expect(
562 await screen.findByRole('heading', { name: 'Not Found' }),
563 ).toBeInTheDocument()
564β
565 expect(window.location.pathname).toBe('/non-existent')
566 })
567β
568 test('navigate function should handle external URLs with ignoreBlocker', async () => {
569 const rootRoute = createRootRoute()
570 const indexRoute = createRoute({
571 getParentRoute: () => rootRoute,
572 path: '/',
573 component: () => <div>Home</div>,
574 })
575β
576 const router = createRouter({
577 routeTree: rootRoute.addChildren([indexRoute]),
578 history: createMemoryHistory({
579 initialEntries: ['/'],
580 }),
581 })
582β
583 await expect(
584 router.navigate({
585 to: 'https://example.com',
586 ignoreBlocker: true,
587 }),
588 ).resolves.toBeUndefined()
589β
590 await expect(
591 router.navigate({
592 to: 'https://example.com',
593 }),
594 ).resolves.toBeUndefined()
595 })
596})