Open History to see the last commit
1import { afterEach, describe, expect, test, vi } from 'vitest'
2import {
3 cleanup,
4 fireEvent,
5 render,
6 screen,
7 waitFor,
8} from '@solidjs/testing-library'
9import { hydrate } from '@tanstack/router-core/ssr/client'
10import { dehydrateSsrMatchId } from '../../router-core/src/ssr/ssr-match-id'
11β
12import {
13 HeadContent,
14 Link,
15 Outlet,
16 RouterContextProvider,
17 RouterProvider,
18 createBrowserHistory,
19 createMemoryHistory,
20 createRootRoute,
21 createRoute,
22 createRouter,
23} from '../src'
24import { Scripts } from '../src/Scripts'
25import type { Manifest } from '@tanstack/router-core'
26β
27const createTestManifest = (
28 routeId: string,
29 options?: { scriptFormat?: Manifest['scriptFormat'] },
30) =>
31 ({
32 ...(options?.scriptFormat ? { scriptFormat: options.scriptFormat } : {}),
33 routes: {
34 [routeId]: {
35 preloads: ['/main.js'],
36 css: ['/main.css'],
37 },
38 },
39 }) satisfies Manifest
40β
41const browserHistories: Array<ReturnType<typeof createBrowserHistory>> = []
42β
43const createTestBrowserHistory = () => {
44 const history = createBrowserHistory()
45 browserHistories.push(history)
46 return history
47}
48β
49afterEach(() => {
50 cleanup()
51 browserHistories.splice(0).forEach((history) => history.destroy())
52 window.history.replaceState(null, 'root', '/')
53 delete window.$_TSR
54})
55β
56describe('ssr scripts', () => {
57 test.each([undefined, '', 'window.inlineRan = true'])(
58 'mounts one external script with children %j and removes it on unmount',
59 async (children) => {
60 const rootRoute = createRootRoute({
61 scripts: () => [{ src: '/external-script.js', children }],
62 component: Scripts,
63 })
64 const router = createRouter({
65 routeTree: rootRoute,
66 history: createMemoryHistory(),
67 })
68 await router.load()
69β
70 const initialScriptCount = document.querySelectorAll('script').length
71 const { unmount } = render(() => <RouterProvider router={router} />)
72 const scripts = document.querySelectorAll(
73 'script[src="/external-script.js"]',
74 )
75 expect(scripts).toHaveLength(1)
76 expect(scripts[0]?.textContent).toBe('')
77 expect(document.querySelectorAll('script')).toHaveLength(
78 initialScriptCount + 1,
79 )
80β
81 unmount()
82 expect(document.querySelectorAll('script')).toHaveLength(
83 initialScriptCount,
84 )
85 expect(
86 document.querySelectorAll('script[src="/external-script.js"]'),
87 ).toHaveLength(0)
88 },
89 )
90β
91 test('updates route data scripts after client navigation', async () => {
92 const rootRoute = createRootRoute({
93 component: () => (
94 <>
95 <Outlet />
96 <Scripts />
97 </>
98 ),
99 })
100 const firstRoute = createRoute({
101 getParentRoute: () => rootRoute,
102 path: '/first',
103 scripts: () => [
104 {
105 id: 'first-route-data',
106 type: 'application/json',
107 children: 'first',
108 },
109 ],
110 component: () => <Link to="/second">Second</Link>,
111 })
112 const secondRoute = createRoute({
113 getParentRoute: () => rootRoute,
114 path: '/second',
115 scripts: () => [
116 {
117 id: 'second-route-data',
118 type: 'application/json',
119 children: 'second',
120 },
121 ],
122 component: () => <div>Second route</div>,
123 })
124 const router = createRouter({
125 routeTree: rootRoute.addChildren([firstRoute, secondRoute]),
126 history: createMemoryHistory({ initialEntries: ['/first'] }),
127 })
128β
129 const { container } = render(() => <RouterProvider router={router} />)
130 await screen.findByRole('link', { name: 'Second' })
131 expect(container.querySelector('#first-route-data')?.textContent).toBe(
132 'first',
133 )
134β
135 fireEvent.click(screen.getByRole('link', { name: 'Second' }))
136 expect(await screen.findByText('Second route')).toBeInTheDocument()
137 await waitFor(() => {
138 expect(container.querySelector('#first-route-data')).toBeNull()
139 expect(container.querySelector('#second-route-data')?.textContent).toBe(
140 'second',
141 )
142 })
143 })
144β
145 test('it works', async () => {
146 const rootRoute = createRootRoute({
147 // loader: () => new Promise((r) => setTimeout(r, 1)),
148 head: () => {
149 return {
150 scripts: [
151 {
152 src: 'script.js',
153 },
154 {
155 src: 'script2.js',
156 },
157 ],
158 }
159 },
160 component: () => {
161 return <Scripts />
162 },
163 })
164β
165 const indexRoute = createRoute({
166 path: '/',
167 getParentRoute: () => rootRoute,
168 // loader: () => new Promise((r) => setTimeout(r, 2)),
169 head: () => {
170 return {
171 scripts: [
172 {
173 src: 'script3.js',
174 },
175 ],
176 }
177 },
178 })
179β
180 const router = createRouter({
181 history: createMemoryHistory({
182 initialEntries: ['/'],
183 }),
184 routeTree: rootRoute.addChildren([indexRoute]),
185 isServer: true,
186 })
187β
188 await router.load()
189β
190 expect(router.state.matches.map((d) => d.headScripts).flat(1)).toEqual([
191 { src: 'script.js' },
192 { src: 'script2.js' },
193 { src: 'script3.js' },
194 ])
195 })
196β
197 test('excludes `undefined` script values', async () => {
198 const rootRoute = createRootRoute({
199 scripts: () => [
200 { src: 'script.js' },
201 undefined, // 'script2.js' opted out by certain conditions, such as `NODE_ENV=production`.
202 ],
203 component: () => {
204 return <Scripts />
205 },
206 })
207β
208 const indexRoute = createRoute({
209 path: '/',
210 getParentRoute: () => rootRoute,
211 scripts: () => [{ src: 'script3.js' }],
212 })
213β
214 const router = createRouter({
215 history: createMemoryHistory({
216 initialEntries: ['/'],
217 }),
218 routeTree: rootRoute.addChildren([indexRoute]),
219 isServer: true,
220 })
221β
222 await router.load()
223β
224 expect(router.state.matches.map((d) => d.scripts).flat(1)).toEqual([
225 { src: 'script.js' },
226 undefined,
227 { src: 'script3.js' },
228 ])
229β
230 const { container } = render(() => <RouterProvider router={router} />)
231β
232 expect(container.innerHTML).toEqual(
233 '<script src="script.js"></script><script src="script3.js"></script>',
234 )
235 })
236β
237 test('keeps manifest stylesheet links mounted across repeated Link navigations', async () => {
238 const history = createTestBrowserHistory()
239β
240 const rootRoute = createRootRoute({
241 component: () => {
242 return (
243 <>
244 <HeadContent />
245 <Outlet />
246 </>
247 )
248 },
249 })
250β
251 const indexRoute = createRoute({
252 path: '/',
253 getParentRoute: () => rootRoute,
254 component: () => <Link to="/about">Go to about page</Link>,
255 })
256β
257 const aboutRoute = createRoute({
258 path: '/about',
259 getParentRoute: () => rootRoute,
260 component: () => <Link to="/">Back to home</Link>,
261 })
262β
263 const router = createRouter({
264 history,
265 routeTree: rootRoute.addChildren([indexRoute, aboutRoute]),
266 })
267β
268 router.ssr = {
269 manifest: createTestManifest(rootRoute.id),
270 }
271β
272 await router.load()
273β
274 render(() => <RouterProvider router={router} />)
275β
276 const getStylesheetLink = () =>
277 Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).find(
278 (link) => link.getAttribute('href') === '/main.css',
279 )
280β
281 await waitFor(() => {
282 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
283 })
284β
285 const initialLink = getStylesheetLink()
286 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
287β
288 for (let i = 0; i < 5; i++) {
289 fireEvent.click(screen.getByRole('link', { name: 'Go to about page' }))
290β
291 await waitFor(() => {
292 expect(router.state.location.pathname).toBe('/about')
293 })
294β
295 await screen.findByRole('link', { name: 'Back to home' })
296β
297 fireEvent.click(screen.getByRole('link', { name: 'Back to home' }))
298β
299 await waitFor(() => {
300 expect(router.state.location.pathname).toBe('/')
301 })
302β
303 await screen.findByRole('link', { name: 'Go to about page' })
304 }
305β
306 expect(getStylesheetLink()).toBe(initialLink)
307 expect(
308 Array.from(
309 document.head.querySelectorAll('link[rel="stylesheet"]'),
310 ).filter((link) => link.getAttribute('href') === '/main.css'),
311 ).toHaveLength(1)
312 })
313β
314 test('keeps manifest stylesheet links mounted when preload counts change', async () => {
315 const history = createTestBrowserHistory()
316β
317 const rootRoute = createRootRoute({
318 component: () => {
319 return (
320 <>
321 <HeadContent />
322 <Outlet />
323 </>
324 )
325 },
326 })
327β
328 const aRoute = createRoute({
329 path: '/a',
330 getParentRoute: () => rootRoute,
331 component: () => <Link to="/b">Go to B</Link>,
332 })
333β
334 const bRoute = createRoute({
335 path: '/b',
336 getParentRoute: () => rootRoute,
337 component: () => <Link to="/a">Go to A</Link>,
338 })
339β
340 const router = createRouter({
341 history,
342 routeTree: rootRoute.addChildren([aRoute, bRoute]),
343 })
344β
345 router.ssr = {
346 manifest: {
347 routes: {
348 [rootRoute.id]: {
349 preloads: ['/root.js'],
350 css: ['/main.css'],
351 },
352 [aRoute.id]: {
353 preloads: ['/a.js'],
354 },
355 [bRoute.id]: {
356 preloads: ['/b.js', '/b-child.js'],
357 },
358 },
359 },
360 }
361β
362 await router.navigate({ to: '/a' })
363 await router.load()
364β
365 render(() => <RouterProvider router={router} />)
366β
367 const getStylesheetLink = () =>
368 Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).find(
369 (link) => link.getAttribute('href') === '/main.css',
370 )
371β
372 await waitFor(() => {
373 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
374 })
375β
376 const initialLink = getStylesheetLink()
377 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
378β
379 fireEvent.click(screen.getByRole('link', { name: 'Go to B' }))
380β
381 await waitFor(() => {
382 expect(router.state.location.pathname).toBe('/b')
383 })
384β
385 await screen.findByRole('link', { name: 'Go to A' })
386β
387 expect(getStylesheetLink()).toBe(initialLink)
388 expect(
389 Array.from(
390 document.head.querySelectorAll('link[rel="stylesheet"]'),
391 ).filter((link) => link.getAttribute('href') === '/main.css'),
392 ).toHaveLength(1)
393 })
394β
395 test('applies assetCrossOrigin to manifest stylesheets and preloads', async () => {
396 const history = createTestBrowserHistory()
397β
398 const rootRoute = createRootRoute({
399 component: () => {
400 return (
401 <>
402 <HeadContent
403 assetCrossOrigin={{
404 script: 'anonymous',
405 stylesheet: 'use-credentials',
406 }}
407 />
408 <Outlet />
409 </>
410 )
411 },
412 })
413β
414 const indexRoute = createRoute({
415 path: '/',
416 getParentRoute: () => rootRoute,
417 component: () => <div>Index</div>,
418 })
419β
420 const router = createRouter({
421 history,
422 routeTree: rootRoute.addChildren([indexRoute]),
423 })
424β
425 router.ssr = {
426 manifest: createTestManifest(rootRoute.id),
427 }
428β
429 await router.load()
430β
431 render(() => <RouterProvider router={router} />)
432β
433 await waitFor(() => {
434 expect(document.head.querySelector('link[rel="stylesheet"]')).toBeTruthy()
435 expect(
436 document.head.querySelector('link[rel="modulepreload"]'),
437 ).toBeTruthy()
438 })
439β
440 expect(
441 document.head
442 .querySelector('link[rel="stylesheet"]')
443 ?.getAttribute('crossorigin'),
444 ).toBe('use-credentials')
445 expect(
446 document.head
447 .querySelector('link[rel="modulepreload"]')
448 ?.getAttribute('crossorigin'),
449 ).toBe('anonymous')
450 })
451β
452 test('renders runtime manifest inlineStyle', async () => {
453 const history = createTestBrowserHistory()
454β
455 const rootRoute = createRootRoute({
456 component: () => {
457 return (
458 <>
459 <HeadContent />
460 <Outlet />
461 </>
462 )
463 },
464 })
465β
466 const indexRoute = createRoute({
467 path: '/',
468 getParentRoute: () => rootRoute,
469 component: () => <div>Index</div>,
470 })
471β
472 const router = createRouter({
473 history,
474 routeTree: rootRoute.addChildren([indexRoute]),
475 })
476β
477 router.ssr = {
478 manifest: {
479 inlineStyle: {
480 attrs: { id: 'runtime-inline-style' },
481 children: '.runtime{color:red}',
482 },
483 routes: {
484 [rootRoute.id]: {},
485 },
486 },
487 }
488β
489 await router.load()
490β
491 render(() => <RouterProvider router={router} />)
492β
493 await waitFor(() => {
494 expect(
495 document.head.querySelector('style#runtime-inline-style'),
496 ).toBeTruthy()
497 })
498β
499 expect(
500 document.head.querySelector('style#runtime-inline-style')?.textContent,
501 ).toBe('.runtime{color:red}')
502 })
503β
504 test('renders preload as script links for iife manifest preloads', async () => {
505 const history = createTestBrowserHistory()
506β
507 const rootRoute = createRootRoute({
508 component: () => {
509 return (
510 <>
511 <HeadContent />
512 <Outlet />
513 </>
514 )
515 },
516 })
517β
518 const indexRoute = createRoute({
519 path: '/',
520 getParentRoute: () => rootRoute,
521 component: () => <div>Index</div>,
522 })
523β
524 const router = createRouter({
525 history,
526 routeTree: rootRoute.addChildren([indexRoute]),
527 })
528β
529 router.ssr = {
530 manifest: createTestManifest(rootRoute.id, { scriptFormat: 'iife' }),
531 }
532β
533 await router.load()
534β
535 render(() => <RouterProvider router={router} />)
536β
537 await waitFor(() => {
538 expect(
539 document.head.querySelector('link[rel="preload"][as="script"]'),
540 ).toBeTruthy()
541 })
542β
543 expect(document.head.querySelector('link[rel="modulepreload"]')).toBeFalsy()
544 })
545})
546β
547describe('ssr HeadContent', () => {
548 test('renders descendant assets during a data-only hydration handoff', async () => {
549 const rootRoute = createRootRoute({})
550 const dataOnlyRoute = createRoute({
551 getParentRoute: () => rootRoute,
552 path: '/report',
553 ssr: 'data-only',
554 loader: () => 'report',
555 })
556 const childRoute = createRoute({
557 getParentRoute: () => dataOnlyRoute,
558 path: '/details',
559 loader: () => 'details',
560 head: () => ({
561 meta: [{ name: 'solid-data-only-child', content: 'visible' }],
562 }),
563 scripts: () => [
564 {
565 id: 'solid-data-only-body-script',
566 type: 'application/json',
567 children: '{"source":"body"}',
568 },
569 ],
570 })
571 const router = createRouter({
572 history: createMemoryHistory({
573 initialEntries: ['/report/details'],
574 }),
575 routeTree: rootRoute.addChildren([
576 dataOnlyRoute.addChildren([childRoute]),
577 ]),
578 })
579 const matches = router.matchRoutes(router.latestLocation)
580 window.$_TSR = {
581 router: {
582 dehydratedData: {},
583 manifest: {
584 routes: {
585 [childRoute.id]: {
586 preloads: ['/solid-data-only-manifest.js'],
587 scripts: [
588 {
589 attrs: {
590 id: 'solid-data-only-manifest-script',
591 type: 'application/json',
592 },
593 children: '{"source":"manifest"}',
594 },
595 ],
596 },
597 },
598 },
599 matches: matches.map((match, index) => ({
600 i: dehydrateSsrMatchId(match.id),
601 s: 'success',
602 ssr: index === 1 ? 'data-only' : true,
603 l: index ? (index === 1 ? 'report' : 'details') : undefined,
604 u: Date.now(),
605 })),
606 },
607 h: vi.fn(),
608 e: vi.fn(),
609 c: vi.fn(),
610 p: vi.fn(),
611 buffer: [],
612 }
613β
614 await hydrate(router)
615β
616 expect(router.state.matches.map((match) => match.status)).toEqual([
617 'success',
618 'pending',
619 'success',
620 ])
621 render(() => (
622 <RouterContextProvider router={router}>
623 {() => (
624 <>
625 <HeadContent />
626 <Scripts />
627 </>
628 )}
629 </RouterContextProvider>
630 ))
631β
632 expect(
633 document.querySelector('meta[name="solid-data-only-child"]'),
634 ).not.toBeNull()
635 expect(
636 document.querySelector('link[href="/solid-data-only-manifest.js"]'),
637 ).not.toBeNull()
638 expect(
639 document.querySelector('#solid-data-only-body-script'),
640 ).not.toBeNull()
641 expect(
642 document.querySelector('#solid-data-only-manifest-script'),
643 ).not.toBeNull()
644 })
645β
646 test('derives title, dedupes meta, and allows non-loader HeadContent', async () => {
647 const rootRoute = createRootRoute({
648 loader: () =>
649 new Promise((r) => setTimeout(r, 1)).then(() => ({
650 description: 'Root',
651 })),
652 head: ({ loaderData }) => {
653 return {
654 meta: [
655 {
656 title: 'Root',
657 },
658 {
659 name: 'description',
660 content: loaderData?.description,
661 },
662 {
663 name: 'image',
664 content: 'image.jpg',
665 },
666 {
667 property: 'og:image',
668 content: 'root-image.jpg',
669 },
670 {
671 property: 'og:description',
672 content: 'Root description',
673 },
674 ],
675 }
676 },
677 component: () => {
678 return <HeadContent />
679 },
680 })
681β
682 const indexRoute = createRoute({
683 path: '/',
684 getParentRoute: () => rootRoute,
685 loader: () =>
686 new Promise((r) => setTimeout(r, 2)).then(() => ({
687 description: 'Index',
688 })),
689 head: ({ loaderData }) => {
690 return {
691 meta: [
692 {
693 title: 'Index',
694 },
695 {
696 name: 'description',
697 content: loaderData?.description,
698 },
699 {
700 name: 'last-modified',
701 content: '2021-10-10',
702 },
703 {
704 property: 'og:image',
705 content: 'index-image.jpg',
706 },
707 ],
708 }
709 },
710 })
711β
712 const router = createRouter({
713 history: createMemoryHistory({
714 initialEntries: ['/'],
715 }),
716 routeTree: rootRoute.addChildren([indexRoute]),
717 isServer: true,
718 })
719β
720 await router.load()
721β
722 expect(router.state.matches.map((d) => d.meta).flat(1)).toEqual([
723 { title: 'Root' },
724 { name: 'description', content: 'Root' },
725 { name: 'image', content: 'image.jpg' },
726 { property: 'og:image', content: 'root-image.jpg' },
727 { property: 'og:description', content: 'Root description' },
728 { title: 'Index' },
729 { name: 'description', content: 'Index' },
730 { name: 'last-modified', content: '2021-10-10' },
731 { property: 'og:image', content: 'index-image.jpg' },
732 ])
733 })
734β
735 test('keeps manifest stylesheet links mounted when history state changes', async () => {
736 const history = createTestBrowserHistory()
737β
738 const rootRoute = createRootRoute({
739 component: () => {
740 return (
741 <>
742 <HeadContent />
743 <button
744 onClick={() => {
745 window.history.replaceState(
746 { slideId: 'slide-2' },
747 '',
748 window.location.href,
749 )
750 }}
751 >
752 Replace state
753 </button>
754 <Outlet />
755 </>
756 )
757 },
758 })
759β
760 const indexRoute = createRoute({
761 path: '/',
762 getParentRoute: () => rootRoute,
763 component: () => <div>Index</div>,
764 })
765β
766 const router = createRouter({
767 history,
768 routeTree: rootRoute.addChildren([indexRoute]),
769 })
770β
771 router.ssr = {
772 manifest: createTestManifest(rootRoute.id),
773 }
774β
775 await router.load()
776β
777 render(() => <RouterProvider router={router} />)
778β
779 const getStylesheetLink = () =>
780 Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).find(
781 (link) => link.getAttribute('href') === '/main.css',
782 )
783β
784 await waitFor(() => {
785 expect(getStylesheetLink()).toBeInstanceOf(HTMLLinkElement)
786 })
787β
788 const initialLink = getStylesheetLink()
789 expect(initialLink).toBeInstanceOf(HTMLLinkElement)
790β
791 fireEvent.click(screen.getByRole('button', { name: 'Replace state' }))
792β
793 await waitFor(() => {
794 expect(router.state.location.state).toMatchObject({
795 slideId: 'slide-2',
796 })
797 })
798β
799 expect(getStylesheetLink()).toBe(initialLink)
800 expect(
801 Array.from(
802 document.head.querySelectorAll('link[rel="stylesheet"]'),
803 ).filter((link) => link.getAttribute('href') === '/main.css'),
804 ).toHaveLength(1)
805 })
806})