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