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

useBlocker.test.tsx

443 lines10.2 KB

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 createRootRoute,
11 createRoute,
12 createRouter,
13 useBlocker,
14 useNavigate,
15} from '../src'
16import type { RouterHistory } from '../src'
17​
18let history: RouterHistory
19​
20beforeEach(() => {
21 history = createBrowserHistory()
22 expect(window.location.pathname).toBe('/')
23})
24​
25afterEach(() => {
26 history.destroy()
27 window.history.replaceState(null, 'root', '/')
28 vi.clearAllMocks()
29 vi.resetAllMocks()
30 cleanup()
31})
32​
33describe('useBlocker', () => {
34 test('does not block navigation when not enabled', async () => {
35 const rootRoute = createRootRoute()
36​
37 const IndexComponent = () => {
38 const navigate = useNavigate()
39​
40 useBlocker({ shouldBlockFn: () => false })
41​
42 return (
43 <>
44 <h1>Index</h1>
45 <button onClick={() => navigate({ to: '/' })}>Index</button>
46 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
47 </>
48 )
49 }
50​
51 const indexRoute = createRoute({
52 getParentRoute: () => rootRoute,
53 path: '/',
54 component: IndexComponent,
55 })
56​
57 const postsRoute = createRoute({
58 getParentRoute: () => rootRoute,
59 path: '/posts',
60 component: () => {
61 return (
62 <>
63 <h1>Posts</h1>
64 </>
65 )
66 },
67 })
68​
69 const router = createRouter({
70 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
71 history,
72 })
73​
74 render(<RouterProvider router={router} />)
75​
76 const postsButton = await screen.findByRole('button', { name: 'Posts' })
77​
78 fireEvent.click(postsButton)
79​
80 expect(
81 await screen.findByRole('heading', { name: 'Posts' }),
82 ).toBeInTheDocument()
83​
84 expect(window.location.pathname).toBe('/posts')
85 })
86​
87 test('does not block navigation when disabled', async () => {
88 const rootRoute = createRootRoute()
89​
90 const IndexComponent = () => {
91 const navigate = useNavigate()
92​
93 useBlocker({ shouldBlockFn: () => true, disabled: true })
94​
95 return (
96 <>
97 <h1>Index</h1>
98 <button onClick={() => navigate({ to: '/' })}>Index</button>
99 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
100 </>
101 )
102 }
103​
104 const indexRoute = createRoute({
105 getParentRoute: () => rootRoute,
106 path: '/',
107 component: IndexComponent,
108 })
109​
110 const postsRoute = createRoute({
111 getParentRoute: () => rootRoute,
112 path: '/posts',
113 component: () => {
114 return (
115 <>
116 <h1>Posts</h1>
117 </>
118 )
119 },
120 })
121​
122 const router = createRouter({
123 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
124 history,
125 })
126​
127 render(<RouterProvider router={router} />)
128​
129 const postsButton = await screen.findByRole('button', { name: 'Posts' })
130​
131 fireEvent.click(postsButton)
132​
133 expect(
134 await screen.findByRole('heading', { name: 'Posts' }),
135 ).toBeInTheDocument()
136​
137 expect(window.location.pathname).toBe('/posts')
138 })
139​
140 test('blocks navigation when enabled', async () => {
141 const rootRoute = createRootRoute()
142​
143 const IndexComponent = () => {
144 const navigate = useNavigate()
145​
146 useBlocker({ shouldBlockFn: () => true })
147​
148 return (
149 <>
150 <h1>Index</h1>
151 <button onClick={() => navigate({ to: '/' })}>Index</button>
152 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
153 </>
154 )
155 }
156​
157 const indexRoute = createRoute({
158 getParentRoute: () => rootRoute,
159 path: '/',
160 component: IndexComponent,
161 })
162​
163 const postsRoute = createRoute({
164 getParentRoute: () => rootRoute,
165 path: '/posts',
166 component: () => {
167 return (
168 <>
169 <h1>Posts</h1>
170 </>
171 )
172 },
173 })
174​
175 const router = createRouter({
176 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
177 history,
178 })
179​
180 render(<RouterProvider router={router} />)
181​
182 const postsButton = await screen.findByRole('button', { name: 'Posts' })
183​
184 fireEvent.click(postsButton)
185​
186 expect(
187 await screen.findByRole('heading', { name: 'Index' }),
188 ).toBeInTheDocument()
189​
190 expect(window.location.pathname).toBe('/')
191 })
192​
193 test('gives correct arguments to shouldBlockFn', async () => {
194 const rootRoute = createRootRoute()
195​
196 const shouldBlockFn = vi.fn().mockReturnValue(true)
197​
198 const IndexComponent = () => {
199 const navigate = useNavigate()
200​
201 useBlocker({ shouldBlockFn })
202​
203 return (
204 <>
205 <h1>Index</h1>
206 <button onClick={() => navigate({ to: '/' })}>Index</button>
207 <button onClick={() => navigate({ to: '/posts', replace: true })}>
208 Posts
209 </button>
210 </>
211 )
212 }
213​
214 const indexRoute = createRoute({
215 getParentRoute: () => rootRoute,
216 path: '/',
217 component: IndexComponent,
218 })
219​
220 const postsRoute = createRoute({
221 getParentRoute: () => rootRoute,
222 path: '/posts',
223 component: () => {
224 return (
225 <>
226 <h1>Posts</h1>
227 </>
228 )
229 },
230 })
231​
232 const router = createRouter({
233 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
234 history,
235 })
236​
237 render(<RouterProvider router={router} />)
238​
239 const postsButton = await screen.findByRole('button', { name: 'Posts' })
240​
241 fireEvent.click(postsButton)
242​
243 expect(
244 await screen.findByRole('heading', { name: 'Index' }),
245 ).toBeInTheDocument()
246​
247 expect(window.location.pathname).toBe('/')
248​
249 expect(shouldBlockFn).toHaveBeenCalledWith({
250 action: 'REPLACE',
251 current: {
252 routeId: indexRoute.id,
253 fullPath: indexRoute.fullPath,
254 pathname: '/',
255 params: {},
256 search: {},
257 },
258 next: {
259 routeId: postsRoute.id,
260 fullPath: postsRoute.fullPath,
261 pathname: '/posts',
262 params: {},
263 search: {},
264 },
265 })
266 })
267​
268 test('gives correct arguments to shouldBlockFn with path and search params', async () => {
269 const rootRoute = createRootRoute()
270​
271 const shouldBlockFn = vi.fn().mockReturnValue(true)
272​
273 const IndexComponent = () => {
274 const navigate = useNavigate()
275​
276 useBlocker({ shouldBlockFn })
277​
278 return (
279 <>
280 <h1>Index</h1>
281 <button onClick={() => navigate({ to: '/' })}>Index</button>
282 <button
283 onClick={() =>
284 navigate({
285 to: '/posts/$postId',
286 params: { postId: '10' },
287 search: { param1: 'foo', param2: 'bar' },
288 })
289 }
290 >
291 Posts
292 </button>
293 </>
294 )
295 }
296​
297 const indexRoute = createRoute({
298 getParentRoute: () => rootRoute,
299 path: '/',
300 component: IndexComponent,
301 })
302​
303 const postsRoute = createRoute({
304 getParentRoute: () => rootRoute,
305 validateSearch: z.object({
306 param1: z.string().default('param1-default'),
307 param2: z.string().default('param2-default'),
308 }),
309 path: '/posts/$postId',
310 component: () => {
311 return (
312 <>
313 <h1>Posts</h1>
314 </>
315 )
316 },
317 })
318​
319 const router = createRouter({
320 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
321 history,
322 })
323​
324 render(<RouterProvider router={router} />)
325​
326 const postsButton = await screen.findByRole('button', { name: 'Posts' })
327​
328 fireEvent.click(postsButton)
329​
330 expect(
331 await screen.findByRole('heading', { name: 'Index' }),
332 ).toBeInTheDocument()
333​
334 expect(window.location.pathname).toBe('/')
335​
336 expect(shouldBlockFn).toHaveBeenCalledWith({
337 action: 'PUSH',
338 current: {
339 routeId: indexRoute.id,
340 fullPath: indexRoute.fullPath,
341 pathname: '/',
342 params: {},
343 search: {},
344 },
345 next: {
346 routeId: postsRoute.id,
347 fullPath: postsRoute.fullPath,
348 pathname: '/posts/10',
349 params: { postId: '10' },
350 search: { param1: 'foo', param2: 'bar' },
351 },
352 })
353 })
354​
355 test('conditionally blocking navigation works', async () => {
356 const rootRoute = createRootRoute()
357​
358 const IndexComponent = () => {
359 const navigate = useNavigate()
360​
361 useBlocker<Router>({
362 shouldBlockFn: ({ next }) => {
363 if (next.fullPath === '/posts') {
364 return true
365 }
366 return false
367 },
368 })
369​
370 return (
371 <>
372 <h1>Index</h1>
373 <button onClick={() => navigate({ to: '/' })}>Index</button>
374 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
375 <button onClick={() => navigate({ to: '/invoices' })}>
376 Invoices
377 </button>
378 </>
379 )
380 }
381​
382 const indexRoute = createRoute({
383 getParentRoute: () => rootRoute,
384 path: '/',
385 component: IndexComponent,
386 })
387​
388 const postsRoute = createRoute({
389 getParentRoute: () => rootRoute,
390 path: '/posts',
391 component: () => {
392 return (
393 <>
394 <h1>Posts</h1>
395 </>
396 )
397 },
398 })
399​
400 const invoicesRoute = createRoute({
401 getParentRoute: () => rootRoute,
402 path: '/invoices',
403 component: () => {
404 return (
405 <>
406 <h1>Invoices</h1>
407 </>
408 )
409 },
410 })
411​
412 const router = createRouter({
413 routeTree: rootRoute.addChildren([indexRoute, postsRoute, invoicesRoute]),
414 history,
415 })
416​
417 type Router = typeof router
418​
419 render(<RouterProvider router={router} />)
420​
421 const postsButton = await screen.findByRole('button', { name: 'Posts' })
422​
423 fireEvent.click(postsButton)
424​
425 expect(
426 await screen.findByRole('heading', { name: 'Index' }),
427 ).toBeInTheDocument()
428​
429 expect(window.location.pathname).toBe('/')
430​
431 const invoicesButton = await screen.findByRole('button', {
432 name: 'Invoices',
433 })
434​
435 fireEvent.click(invoicesButton)
436​
437 expect(
438 await screen.findByRole('heading', { name: 'Invoices' }),
439 ).toBeInTheDocument()
440​
441 expect(window.location.pathname).toBe('/invoices')
442 })
443})