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

useBlocker.test.tsx

645 lines15.1 KB

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