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

route.test.tsx

575 lines15.7 KB

1import React from 'react'
2import { afterEach, beforeEach, describe, expect, it, test, vi } from 'vitest'
3import { cleanup, render, screen } from '@testing-library/react'
4​
5import {
6 RouterProvider,
7 createBrowserHistory,
8 createRootRoute,
9 createRoute,
10 createRouter,
11 getRouteApi,
12 notFound,
13} from '../src'
14import type { RouterHistory } from '../src'
15​
16let history: RouterHistory
17​
18beforeEach(() => {
19 history = createBrowserHistory()
20 expect(window.location.pathname).toBe('/')
21})
22​
23afterEach(() => {
24 history.destroy()
25 vi.resetAllMocks()
26 window.history.replaceState(null, 'root', '/')
27 cleanup()
28})
29​
30describe('getRouteApi', () => {
31 it('should have the useMatch hook', () => {
32 const api = getRouteApi('foo')
33 expect(api.useMatch).toBeDefined()
34 })
35​
36 it('should have the useRouteContext hook', () => {
37 const api = getRouteApi('foo')
38 expect(api.useRouteContext).toBeDefined()
39 })
40​
41 it('should have the useSearch hook', () => {
42 const api = getRouteApi('foo')
43 expect(api.useSearch).toBeDefined()
44 })
45​
46 it('should have the useParams hook', () => {
47 const api = getRouteApi('foo')
48 expect(api.useParams).toBeDefined()
49 })
50​
51 it('should have the useLoaderData hook', () => {
52 const api = getRouteApi('foo')
53 expect(api.useLoaderData).toBeDefined()
54 })
55​
56 it('should have the useLoaderDeps hook', () => {
57 const api = getRouteApi('foo')
58 expect(api.useLoaderDeps).toBeDefined()
59 })
60​
61 it('should have the useNavigate hook', () => {
62 const api = getRouteApi('foo')
63 expect(api.useNavigate).toBeDefined()
64 })
65})
66​
67describe('createRoute has the same hooks as getRouteApi', () => {
68 const routeApi = getRouteApi('foo')
69 const hookNames = Object.keys(routeApi).filter((key) => key.startsWith('use'))
70 const route = createRoute({} as any)
71​
72 it.each(hookNames.map((name) => [name]))(
73 'should have the "%s" hook defined',
74 (hookName) => {
75 expect(route[hookName as keyof typeof route]).toBeDefined()
76 },
77 )
78})
79​
80/* disabled until HMR bug is fixed
81describe('throws invariant exception when trying to access properties before `createRouter` completed', () => {
82 function setup() {
83 const rootRoute = createRootRoute()
84​
85 const IndexComponent = () => {
86 const navigate = useNavigate()
87 return (
88 <>
89 <h1>Index</h1>
90 <button onClick={() => navigate({ to: '/' })}>Index</button>
91 <button onClick={() => navigate({ to: '/posts' })}>Posts</button>
92 </>
93 )
94 }
95​
96 const indexRoute = createRoute({
97 getParentRoute: () => rootRoute,
98 path: '/',
99 component: IndexComponent,
100 })
101​
102 const postsRoute = createRoute({
103 getParentRoute: () => rootRoute,
104 path: '/posts',
105 component: () => {
106 return (
107 <>
108 <h1>Posts</h1>
109 </>
110 )
111 },
112 })
113 const initRouter = () =>
114 createRouter({
115 routeTree: rootRoute.addChildren([indexRoute, postsRoute]),
116 })
117 return { initRouter, rootRoute, indexRoute, postsRoute }
118 }
119​
120 it('to', () => {
121 const { initRouter, indexRoute, postsRoute } = setup()
122​
123 const expectedError = `Invariant failed: trying to access property 'to' on a route which is not initialized yet. Route properties are only available after 'createRouter' completed.`
124 expect(() => indexRoute.to).toThrowError(expectedError)
125 expect(() => postsRoute.to).toThrowError(expectedError)
126​
127 initRouter()
128​
129 expect(indexRoute.to).toBe('/')
130 expect(postsRoute.to).toBe('/posts')
131 })
132​
133 it('fullPath', () => {
134 const { initRouter, indexRoute, postsRoute } = setup()
135​
136 const expectedError = `trying to access property 'fullPath' on a route which is not initialized yet. Route properties are only available after 'createRouter' completed.`
137 expect(() => indexRoute.fullPath).toThrowError(expectedError)
138 expect(() => postsRoute.fullPath).toThrowError(expectedError)
139​
140 initRouter()
141​
142 expect(indexRoute.fullPath).toBe('/')
143 expect(postsRoute.fullPath).toBe('/posts')
144 })
145​
146 it('id', () => {
147 const { initRouter, indexRoute, postsRoute } = setup()
148​
149 const expectedError = `Invariant failed: trying to access property 'id' on a route which is not initialized yet. Route properties are only available after 'createRouter' completed.`
150 expect(() => indexRoute.id).toThrowError(expectedError)
151 expect(() => postsRoute.id).toThrowError(expectedError)
152​
153 initRouter()
154​
155 expect(indexRoute.to).toBe('/')
156 expect(postsRoute.to).toBe('/posts')
157 })
158})
159*/
160​
161describe('onEnter event', () => {
162 it('should have router context defined in router.load()', async () => {
163 const fn = vi.fn()
164 const rootRoute = createRootRoute()
165 const indexRoute = createRoute({
166 getParentRoute: () => rootRoute,
167 path: '/',
168 component: () => {
169 return <h1>Index</h1>
170 },
171 onEnter: ({ context }) => {
172 fn(context)
173 },
174 })
175 const routeTree = rootRoute.addChildren([indexRoute])
176 const router = createRouter({ routeTree, context: { foo: 'bar' }, history })
177​
178 await router.load()
179​
180 expect(fn).toHaveBeenCalledWith({ foo: 'bar' })
181 })
182​
183 it('should have router context defined in <RouterProvider router={router} />', async () => {
184 const fn = vi.fn()
185 const rootRoute = createRootRoute()
186 const indexRoute = createRoute({
187 getParentRoute: () => rootRoute,
188 path: '/',
189 component: () => {
190 return <h1>Index</h1>
191 },
192 onEnter: ({ context }) => {
193 fn(context)
194 },
195 })
196 const routeTree = rootRoute.addChildren([indexRoute])
197 const router = createRouter({ routeTree, context: { foo: 'bar' }, history })
198​
199 render(<RouterProvider router={router} />)
200​
201 const indexElem = await screen.findByText('Index')
202 expect(indexElem).toBeInTheDocument()
203​
204 expect(fn).toHaveBeenCalledWith({ foo: 'bar' })
205 })
206})
207​
208describe('route.head', () => {
209 test('meta', async () => {
210 const rootRoute = createRootRoute({
211 head: () => ({
212 meta: [
213 { title: 'Root' },
214 {
215 charSet: 'utf-8',
216 },
217 ],
218 }),
219 })
220 const indexRoute = createRoute({
221 getParentRoute: () => rootRoute,
222 path: '/',
223 head: () => ({
224 meta: [{ title: 'Index' }],
225 }),
226 component: () => <div>Index</div>,
227 })
228 const routeTree = rootRoute.addChildren([indexRoute])
229 const router = createRouter({ routeTree, history })
230 render(<RouterProvider router={router} />)
231 const indexElem = await screen.findByText('Index')
232 expect(indexElem).toBeInTheDocument()
233​
234 const metaState = router.state.matches.map((m) => m.meta)
235 expect(metaState).toEqual([
236 [
237 { title: 'Root' },
238 {
239 charSet: 'utf-8',
240 },
241 ],
242 [{ title: 'Index' }],
243 ])
244 })
245​
246 test('meta w/ loader', async () => {
247 const rootRoute = createRootRoute({
248 head: () => ({
249 meta: [
250 { title: 'Root' },
251 {
252 charSet: 'utf-8',
253 },
254 ],
255 }),
256 })
257 const indexRoute = createRoute({
258 getParentRoute: () => rootRoute,
259 path: '/',
260 head: () => ({
261 meta: [{ title: 'Index' }],
262 }),
263 loader: async () => {
264 await new Promise((resolve) => setTimeout(resolve, 200))
265 },
266 component: () => <div>Index</div>,
267 })
268 const routeTree = rootRoute.addChildren([indexRoute])
269 const router = createRouter({ routeTree, history })
270 render(<RouterProvider router={router} />)
271 const indexElem = await screen.findByText('Index')
272 expect(indexElem).toBeInTheDocument()
273​
274 const metaState = router.state.matches.map((m) => m.meta)
275 expect(metaState).toEqual([
276 [
277 { title: 'Root' },
278 {
279 charSet: 'utf-8',
280 },
281 ],
282 [{ title: 'Index' }],
283 ])
284 })
285​
286 test('meta is set when loader throws notFound', async () => {
287 const rootRoute = createRootRoute({
288 head: () => ({
289 meta: [
290 { title: 'Root' },
291 {
292 charSet: 'utf-8',
293 },
294 ],
295 }),
296 })
297 const indexRoute = createRoute({
298 getParentRoute: () => rootRoute,
299 path: '/',
300 head: () => ({
301 meta: [{ title: 'Index' }],
302 }),
303 loader: async () => {
304 throw notFound()
305 },
306 component: () => <div>Index</div>,
307 })
308 const routeTree = rootRoute.addChildren([indexRoute])
309 const router = createRouter({ routeTree })
310 render(<RouterProvider router={router} />)
311 expect(await screen.findByText('Not Found')).toBeInTheDocument()
312​
313 const metaState = router.state.matches.map((m) => m.meta)
314 expect(metaState).toEqual([
315 [
316 { title: 'Root' },
317 {
318 charSet: 'utf-8',
319 },
320 ],
321 [{ title: 'Index' }],
322 ])
323 })
324​
325 test('meta is set when loader throws an error', async () => {
326 const rootRoute = createRootRoute({
327 head: () => ({
328 meta: [
329 { title: 'Root' },
330 {
331 charSet: 'utf-8',
332 },
333 ],
334 }),
335 })
336 const indexRoute = createRoute({
337 getParentRoute: () => rootRoute,
338 path: '/',
339 head: () => ({
340 meta: [{ title: 'Index' }],
341 }),
342 loader: async () => {
343 throw new Error('Fly, you fools!')
344 },
345 component: () => <div>Index</div>,
346 })
347 const routeTree = rootRoute.addChildren([indexRoute])
348 const router = createRouter({ routeTree })
349 render(<RouterProvider router={router} />)
350​
351 expect(await screen.findByText('Fly, you fools!')).toBeInTheDocument()
352​
353 const metaState = router.state.matches.map((m) => m.meta)
354 expect(metaState).toEqual([
355 [
356 { title: 'Root' },
357 {
358 charSet: 'utf-8',
359 },
360 ],
361 [{ title: 'Index' }],
362 ])
363 })
364​
365 test('scripts', async () => {
366 const rootRoute = createRootRoute({
367 head: () => ({
368 scripts: [{ src: 'root.js' }, { src: 'root2.js' }],
369 }),
370 })
371 const indexRoute = createRoute({
372 getParentRoute: () => rootRoute,
373 path: '/',
374 head: () => ({
375 scripts: [{ src: 'index.js' }],
376 }),
377 component: () => <div>Index</div>,
378 })
379 const routeTree = rootRoute.addChildren([indexRoute])
380 const router = createRouter({ routeTree, history })
381 render(<RouterProvider router={router} />)
382 const indexElem = await screen.findByText('Index')
383 expect(indexElem).toBeInTheDocument()
384​
385 const scriptsState = router.state.matches.map((m) => m.headScripts)
386 expect(scriptsState).toEqual([
387 [{ src: 'root.js' }, { src: 'root2.js' }],
388 [{ src: 'index.js' }],
389 ])
390 })
391​
392 test('scripts w/ loader', async () => {
393 const rootRoute = createRootRoute({
394 head: () => ({
395 scripts: [{ src: 'root.js' }, { src: 'root2.js' }],
396 }),
397 })
398 const indexRoute = createRoute({
399 getParentRoute: () => rootRoute,
400 path: '/',
401 head: () => ({
402 scripts: [{ src: 'index.js' }],
403 }),
404 loader: async () => {
405 await new Promise((resolve) => setTimeout(resolve, 200))
406 },
407 component: () => <div>Index</div>,
408 })
409 const routeTree = rootRoute.addChildren([indexRoute])
410 const router = createRouter({ routeTree, history })
411 render(<RouterProvider router={router} />)
412 const indexElem = await screen.findByText('Index')
413 expect(indexElem).toBeInTheDocument()
414​
415 const scriptsState = router.state.matches.map((m) => m.headScripts)
416 expect(scriptsState).toEqual([
417 [{ src: 'root.js' }, { src: 'root2.js' }],
418 [{ src: 'index.js' }],
419 ])
420 })
421​
422 test('links', async () => {
423 const rootRoute = createRootRoute({
424 head: () => ({
425 links: [{ href: 'root.css' }, { href: 'root2.css' }],
426 }),
427 })
428 const indexRoute = createRoute({
429 getParentRoute: () => rootRoute,
430 path: '/',
431 head: () => ({
432 links: [{ href: 'index.css' }],
433 }),
434 component: () => <div>Index</div>,
435 })
436 const routeTree = rootRoute.addChildren([indexRoute])
437 const router = createRouter({ routeTree, history })
438 render(<RouterProvider router={router} />)
439 const indexElem = await screen.findByText('Index')
440 expect(indexElem).toBeInTheDocument()
441​
442 const linksState = router.state.matches.map((m) => m.links)
443 expect(linksState).toEqual([
444 [{ href: 'root.css' }, { href: 'root2.css' }],
445 [{ href: 'index.css' }],
446 ])
447 })
448​
449 test('links w/loader', async () => {
450 const rootRoute = createRootRoute({
451 head: () => ({
452 links: [{ href: 'root.css' }, { href: 'root2.css' }],
453 }),
454 })
455 const indexRoute = createRoute({
456 getParentRoute: () => rootRoute,
457 path: '/',
458 head: () => ({
459 links: [{ href: 'index.css' }],
460 }),
461 loader: async () => {
462 await new Promise((resolve) => setTimeout(resolve, 200))
463 },
464 component: () => <div>Index</div>,
465 })
466 const routeTree = rootRoute.addChildren([indexRoute])
467 const router = createRouter({ routeTree, history })
468 render(<RouterProvider router={router} />)
469 const indexElem = await screen.findByText('Index')
470 expect(indexElem).toBeInTheDocument()
471​
472 const linksState = router.state.matches.map((m) => m.links)
473 expect(linksState).toEqual([
474 [{ href: 'root.css' }, { href: 'root2.css' }],
475 [{ href: 'index.css' }],
476 ])
477 })
478​
479 test('styles', async () => {
480 const rootRoute = createRootRoute({
481 head: () => ({
482 styles: [
483 {
484 media: 'all and (min-width: 200px)',
485 children: '.inline-div { color: blue; }',
486 },
487 ],
488 }),
489 })
490 const indexRoute = createRoute({
491 getParentRoute: () => rootRoute,
492 path: '/',
493 head: () => ({
494 styles: [
495 {
496 media: 'all and (min-width: 100px)',
497 children: '.inline-div { background-color: yellow; }',
498 },
499 ],
500 }),
501 component: () => <div className="inline-div">Index</div>,
502 })
503 const routeTree = rootRoute.addChildren([indexRoute])
504 const router = createRouter({ routeTree, history })
505 render(<RouterProvider router={router} />)
506 const indexElem = await screen.findByText('Index')
507 expect(indexElem).toBeInTheDocument()
508​
509 const stylesState = router.state.matches.map((m) => m.styles)
510 expect(stylesState).toEqual([
511 [
512 {
513 media: 'all and (min-width: 200px)',
514 children: '.inline-div { color: blue; }',
515 },
516 ],
517 [
518 {
519 media: 'all and (min-width: 100px)',
520 children: '.inline-div { background-color: yellow; }',
521 },
522 ],
523 ])
524 })
525​
526 test('styles w/loader', async () => {
527 const rootRoute = createRootRoute({
528 head: () => ({
529 styles: [
530 {
531 media: 'all and (min-width: 200px)',
532 children: '.inline-div { color: blue; }',
533 },
534 ],
535 }),
536 })
537 const indexRoute = createRoute({
538 getParentRoute: () => rootRoute,
539 path: '/',
540 head: () => ({
541 styles: [
542 {
543 media: 'all and (min-width: 100px)',
544 children: '.inline-div { background-color: yellow; }',
545 },
546 ],
547 }),
548 loader: async () => {
549 await new Promise((resolve) => setTimeout(resolve, 200))
550 },
551 component: () => <div className="inline-div">Index</div>,
552 })
553 const routeTree = rootRoute.addChildren([indexRoute])
554 const router = createRouter({ routeTree, history })
555 render(<RouterProvider router={router} />)
556 const indexElem = await screen.findByText('Index')
557 expect(indexElem).toBeInTheDocument()
558​
559 const stylesState = router.state.matches.map((m) => m.styles)
560 expect(stylesState).toEqual([
561 [
562 {
563 media: 'all and (min-width: 200px)',
564 children: '.inline-div { color: blue; }',
565 },
566 ],
567 [
568 {
569 media: 'all and (min-width: 100px)',
570 children: '.inline-div { background-color: yellow; }',
571 },
572 ],
573 ])
574 })
575})