-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathHydrationBoundary.test.tsx
More file actions
609 lines (513 loc) · 17.8 KB
/
HydrationBoundary.test.tsx
File metadata and controls
609 lines (513 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import * as React from 'react'
import { render } from '@testing-library/react'
import * as coreModule from '@tanstack/query-core'
import { sleep } from '@tanstack/query-test-utils'
import {
HydrationBoundary,
QueryClient,
QueryClientProvider,
defaultShouldDehydrateQuery,
dehydrate,
useQuery,
useSuspenseQuery,
} from '..'
import type { hydrate } from '@tanstack/query-core'
describe('React hydration', () => {
let stringifiedState: string
beforeEach(async () => {
vi.useFakeTimers()
const queryClient = new QueryClient()
queryClient.prefetchQuery({
queryKey: ['string'],
queryFn: () => sleep(10).then(() => ['stringCached']),
})
await vi.advanceTimersByTimeAsync(10)
const dehydrated = dehydrate(queryClient)
stringifiedState = JSON.stringify(dehydrated)
queryClient.clear()
})
afterEach(() => {
vi.useRealTimers()
})
test('should hydrate queries to the cache on context', async () => {
const dehydratedState = JSON.parse(stringifiedState)
const queryClient = new QueryClient()
function Page() {
const { data } = useQuery({
queryKey: ['string'],
queryFn: () => sleep(20).then(() => ['string']),
})
return (
<div>
<h1>{data}</h1>
</div>
)
}
const rendered = render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={dehydratedState}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
expect(rendered.getByText('stringCached')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(21)
expect(rendered.getByText('string')).toBeInTheDocument()
queryClient.clear()
})
test('should hydrate queries to the cache on custom context', async () => {
const queryClientInner = new QueryClient()
const queryClientOuter = new QueryClient()
const dehydratedState = JSON.parse(stringifiedState)
function Page() {
const { data } = useQuery({
queryKey: ['string'],
queryFn: () => sleep(20).then(() => ['string']),
})
return (
<div>
<h1>{data}</h1>
</div>
)
}
const rendered = render(
<QueryClientProvider client={queryClientOuter}>
<QueryClientProvider client={queryClientInner}>
<HydrationBoundary state={dehydratedState}>
<Page />
</HydrationBoundary>
</QueryClientProvider>
</QueryClientProvider>,
)
expect(rendered.getByText('stringCached')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(21)
expect(rendered.getByText('string')).toBeInTheDocument()
queryClientInner.clear()
queryClientOuter.clear()
})
describe('ReactQueryCacheProvider with hydration support', () => {
test('should hydrate new queries if queries change', async () => {
const dehydratedState = JSON.parse(stringifiedState)
const queryClient = new QueryClient()
function Page({ queryKey }: { queryKey: [string] }) {
const { data } = useQuery({
queryKey,
queryFn: () => sleep(20).then(() => queryKey),
})
return (
<div>
<h1>{data}</h1>
</div>
)
}
const rendered = render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={dehydratedState}>
<Page queryKey={['string']} />
</HydrationBoundary>
</QueryClientProvider>,
)
expect(rendered.getByText('stringCached')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(21)
expect(rendered.getByText('string')).toBeInTheDocument()
const intermediateClient = new QueryClient()
intermediateClient.prefetchQuery({
queryKey: ['string'],
queryFn: () => sleep(20).then(() => ['should change']),
})
intermediateClient.prefetchQuery({
queryKey: ['added'],
queryFn: () => sleep(20).then(() => ['added']),
})
await vi.advanceTimersByTimeAsync(20)
const dehydrated = dehydrate(intermediateClient)
intermediateClient.clear()
rendered.rerender(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={dehydrated}>
<Page queryKey={['string']} />
<Page queryKey={['added']} />
</HydrationBoundary>
</QueryClientProvider>,
)
// Existing observer should not have updated at this point,
// as that would indicate a side effect in the render phase
expect(rendered.getByText('string')).toBeInTheDocument()
// New query data should be available immediately
expect(rendered.getByText('added')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(0)
// After effects phase has had time to run, the observer should have updated
expect(rendered.queryByText('string')).not.toBeInTheDocument()
expect(rendered.getByText('should change')).toBeInTheDocument()
queryClient.clear()
})
// When we hydrate in transitions that are later aborted, it could be
// confusing to both developers and users if we suddenly updated existing
// state on the screen (why did this update when it was not stale, nothing
// remounted, I didn't change tabs etc?).
// Any queries that does not exist in the cache yet can still be hydrated
// since they don't have any observers on the current page that would update.
test('should hydrate new but not existing queries if transition is aborted', async () => {
const initialDehydratedState = JSON.parse(stringifiedState)
const queryClient = new QueryClient()
function Page({ queryKey }: { queryKey: [string] }) {
const { data } = useQuery({
queryKey,
queryFn: () => sleep(20).then(() => queryKey),
})
return (
<div>
<h1>{data}</h1>
</div>
)
}
const rendered = render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={initialDehydratedState}>
<Page queryKey={['string']} />
</HydrationBoundary>
</QueryClientProvider>,
)
expect(rendered.getByText('stringCached')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(21)
expect(rendered.getByText('string')).toBeInTheDocument()
const intermediateClient = new QueryClient()
intermediateClient.prefetchQuery({
queryKey: ['string'],
queryFn: () => sleep(20).then(() => ['should not change']),
})
intermediateClient.prefetchQuery({
queryKey: ['added'],
queryFn: () => sleep(20).then(() => ['added']),
})
await vi.advanceTimersByTimeAsync(20)
const newDehydratedState = dehydrate(intermediateClient)
intermediateClient.clear()
function Thrower(): never {
throw new Promise(() => {
// Never resolve
})
}
React.startTransition(() => {
rendered.rerender(
<React.Suspense fallback="loading">
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={newDehydratedState}>
<Page queryKey={['string']} />
<Page queryKey={['added']} />
<Thrower />
</HydrationBoundary>
</QueryClientProvider>
</React.Suspense>,
)
expect(rendered.getByText('loading')).toBeInTheDocument()
})
React.startTransition(() => {
rendered.rerender(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={initialDehydratedState}>
<Page queryKey={['string']} />
<Page queryKey={['added']} />
</HydrationBoundary>
</QueryClientProvider>,
)
// This query existed before the transition so it should stay the same
expect(rendered.getByText('string')).toBeInTheDocument()
expect(
rendered.queryByText('should not change'),
).not.toBeInTheDocument()
// New query data should be available immediately because it was
// hydrated in the previous transition, even though the new dehydrated
// state did not contain it
expect(rendered.getByText('added')).toBeInTheDocument()
})
await vi.advanceTimersByTimeAsync(20)
// It should stay the same even after effects have had a chance to run
expect(rendered.getByText('string')).toBeInTheDocument()
expect(rendered.queryByText('should not change')).not.toBeInTheDocument()
queryClient.clear()
})
test('should hydrate queries to new cache if cache changes', async () => {
const dehydratedState = JSON.parse(stringifiedState)
const queryClient = new QueryClient()
function Page() {
const { data } = useQuery({
queryKey: ['string'],
queryFn: () => sleep(20).then(() => ['string']),
})
return (
<div>
<h1>{data}</h1>
</div>
)
}
const rendered = render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={dehydratedState}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
expect(rendered.getByText('stringCached')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(21)
expect(rendered.getByText('string')).toBeInTheDocument()
const newClientQueryClient = new QueryClient()
rendered.rerender(
<QueryClientProvider client={newClientQueryClient}>
<HydrationBoundary state={dehydratedState}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
await vi.advanceTimersByTimeAsync(20)
expect(rendered.getByText('string')).toBeInTheDocument()
queryClient.clear()
newClientQueryClient.clear()
})
})
test('should not hydrate queries if state is null', async () => {
const queryClient = new QueryClient()
const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
function Page() {
return null
}
render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={null}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
await Promise.all(
Array.from({ length: 1000 }).map(async (_, index) => {
await vi.advanceTimersByTimeAsync(index)
expect(hydrateSpy).toHaveBeenCalledTimes(0)
}),
)
hydrateSpy.mockRestore()
queryClient.clear()
})
test('should not hydrate queries if state is undefined', async () => {
const queryClient = new QueryClient()
const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
function Page() {
return null
}
render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={undefined}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
await vi.advanceTimersByTimeAsync(0)
expect(hydrateSpy).toHaveBeenCalledTimes(0)
hydrateSpy.mockRestore()
queryClient.clear()
})
test('should not hydrate queries if state is not an object', async () => {
const queryClient = new QueryClient()
const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
function Page() {
return null
}
render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={'invalid-state' as any}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
await vi.advanceTimersByTimeAsync(0)
expect(hydrateSpy).toHaveBeenCalledTimes(0)
hydrateSpy.mockRestore()
queryClient.clear()
})
test('should handle state without queries property gracefully', async () => {
const queryClient = new QueryClient()
const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
function Page() {
return null
}
render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={{} as any}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
await vi.advanceTimersByTimeAsync(0)
expect(hydrateSpy).toHaveBeenCalledTimes(0)
hydrateSpy.mockRestore()
queryClient.clear()
})
// https://github.com/TanStack/query/issues/8677
test('should not infinite loop when hydrating promises that resolve to errors', async () => {
const originalHydrate = coreModule.hydrate
const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
let hydrationCount = 0
hydrateSpy.mockImplementation((...args: Parameters<typeof hydrate>) => {
hydrationCount++
// Arbitrary number
if (hydrationCount > 10) {
// This is a rough way to detect it. Calling hydrate multiple times with
// the same data is usually fine, but in this case it indicates the
// logic in HydrationBoundary is not working as expected.
throw new Error('Too many hydrations detected')
}
return originalHydrate(...args)
})
// For the bug to trigger, there needs to already be a query in the cache,
// with a dataUpdatedAt earlier than the dehydratedAt of the next query
const clientQueryClient = new QueryClient()
clientQueryClient.prefetchQuery({
queryKey: ['promise'],
queryFn: () => sleep(20).then(() => 'existing'),
})
await vi.advanceTimersByTimeAsync(20)
const prefetchQueryClient = new QueryClient({
defaultOptions: {
dehydrate: {
shouldDehydrateQuery: () => true,
},
},
})
prefetchQueryClient.prefetchQuery({
queryKey: ['promise'],
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Query failed'))),
})
const dehydratedState = dehydrate(prefetchQueryClient)
// Mimic what React/our synchronous thenable does for already rejected promises
// @ts-expect-error
dehydratedState.queries[0].promise.status = 'failure'
function Page() {
const { data } = useQuery({
queryKey: ['promise'],
queryFn: () => sleep(20).then(() => ['new']),
})
return (
<div>
<h1>{data}</h1>
</div>
)
}
const rendered = render(
<QueryClientProvider client={clientQueryClient}>
<HydrationBoundary state={dehydratedState}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
expect(rendered.getByText('existing')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(21)
expect(rendered.getByText('new')).toBeInTheDocument()
hydrateSpy.mockRestore()
prefetchQueryClient.clear()
clientQueryClient.clear()
})
test('should hydrate pending idle queries in render to avoid suspense refetches', async () => {
const queryKey = ['string'] as const
const makeQueryClient = () =>
new QueryClient({
defaultOptions: {
dehydrate: {
shouldDehydrateQuery: (query) =>
defaultShouldDehydrateQuery(query) ||
query.state.status === 'pending',
shouldRedactErrors: () => false,
},
},
})
const prefetchClient = makeQueryClient()
void prefetchClient.prefetchQuery({
queryKey,
queryFn: () => Promise.resolve(['stringCached']),
staleTime: Infinity,
})
const dehydratedState = dehydrate(prefetchClient)
const queryFn = vi.fn(() => Promise.resolve(['string']))
const suspenseQueryFn = vi.fn(() => Promise.resolve(['string']))
const queryClient = new QueryClient()
function Header() {
useQuery({
queryKey,
queryFn,
})
return null
}
function Page() {
const { data } = useSuspenseQuery({
queryKey,
queryFn: suspenseQueryFn,
})
return <div>{data}</div>
}
render(
<QueryClientProvider client={queryClient}>
<Header />
<HydrationBoundary state={dehydratedState}>
<React.Suspense fallback="loading">
<Page />
</React.Suspense>
</HydrationBoundary>
</QueryClientProvider>,
)
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
await vi.advanceTimersByTimeAsync(1)
expect(queryClient.getQueryData(queryKey)).toEqual(['stringCached'])
expect(suspenseQueryFn).toHaveBeenCalledTimes(0)
queryClient.clear()
})
test('should not refetch when query has enabled set to false', async () => {
const queryFn = vi.fn()
const queryClient = new QueryClient()
function Page() {
const { data } = useQuery({
queryKey: ['string'],
queryFn,
enabled: false,
})
return <div>{JSON.stringify(data)}</div>
}
const rendered = render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={JSON.parse(stringifiedState)}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
expect(queryFn).toHaveBeenCalledTimes(0)
expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
queryClient.clear()
})
test('should not refetch when query has staleTime set to Infinity', async () => {
const queryFn = vi.fn()
const queryClient = new QueryClient()
function Page() {
const { data } = useQuery({
queryKey: ['string'],
queryFn,
staleTime: Infinity,
})
return <div>{JSON.stringify(data)}</div>
}
const rendered = render(
<QueryClientProvider client={queryClient}>
<HydrationBoundary state={JSON.parse(stringifiedState)}>
<Page />
</HydrationBoundary>
</QueryClientProvider>,
)
expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
expect(queryFn).toHaveBeenCalledTimes(0)
expect(rendered.getByText('["stringCached"]')).toBeInTheDocument()
queryClient.clear()
})
})