Open History to see the last commit
1import { describe, expect, it, vi } from 'vitest'
2import { waitForHydrationPrefetchStrategy } from '../src/hydration/runtime'
3import type { HydrationPrefetchStrategy } from '../src/hydration/types'
4β
5describe('waitForHydrationPrefetchStrategy', () => {
6 it('cleans up a strategy that finishes during synchronous setup', async () => {
7 const abortController = new AbortController()
8 const cleanupHydrate = vi.fn()
9 const cleanupStrategy = vi.fn()
10 let hydrate = () => {}
11β
12 const strategy: HydrationPrefetchStrategy = {
13 _s: ({ prefetch }) => {
14 prefetch?.()
15 return cleanupStrategy
16 },
17 }
18β
19 const result = waitForHydrationPrefetchStrategy(strategy, {
20 element: null,
21 signal: abortController.signal,
22 onHydrate: (listener) => {
23 hydrate = listener
24 return cleanupHydrate
25 },
26 })
27β
28 await expect(result).resolves.toBe('prefetch')
29 expect(cleanupHydrate).toHaveBeenCalledTimes(1)
30 expect(cleanupStrategy).toHaveBeenCalledTimes(1)
31β
32 hydrate()
33 abortController.abort()
34 expect(cleanupHydrate).toHaveBeenCalledTimes(1)
35 expect(cleanupStrategy).toHaveBeenCalledTimes(1)
36 })
37β
38 it.each([
39 ['abort', 'abort'],
40 ['hydrate', 'hydrate'],
41 ] as const)(
42 'settles an abort/hydrate race with %s first and cleans up once',
43 async (winner, expectedReason) => {
44 const abortController = new AbortController()
45 const cleanupHydrate = vi.fn()
46 const cleanupStrategy = vi.fn()
47 let hydrate = () => {}
48 let prefetch = () => {}
49β
50 const strategy: HydrationPrefetchStrategy = {
51 _s: (context) => {
52 prefetch = context.prefetch ?? (() => {})
53 return cleanupStrategy
54 },
55 }
56β
57 const result = waitForHydrationPrefetchStrategy(strategy, {
58 element: null,
59 signal: abortController.signal,
60 onHydrate: (listener) => {
61 hydrate = listener
62 return cleanupHydrate
63 },
64 })
65β
66 if (winner === 'abort') {
67 abortController.abort()
68 hydrate()
69 } else {
70 hydrate()
71 abortController.abort()
72 }
73 prefetch()
74β
75 await expect(result).resolves.toBe(expectedReason)
76 expect(cleanupHydrate).toHaveBeenCalledTimes(1)
77 expect(cleanupStrategy).toHaveBeenCalledTimes(1)
78 },
79 )
80β
81 it('does not set up a strategy when the signal is already aborted', async () => {
82 const abortController = new AbortController()
83 abortController.abort()
84 const setup = vi.fn()
85 const onHydrate = vi.fn()
86β
87 const result = waitForHydrationPrefetchStrategy(
88 { _s: setup },
89 {
90 element: null,
91 signal: abortController.signal,
92 onHydrate,
93 },
94 )
95β
96 await expect(result).resolves.toBe('abort')
97 expect(setup).not.toHaveBeenCalled()
98 expect(onHydrate).not.toHaveBeenCalled()
99 })
100})