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

useBlocker.test.tsx

646 lines15.2 KB

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