Open History to see the last commit
1import * as React from 'react'
2import { render, waitFor } from '@testing-library/react'
3import { vi } from 'vitest'
4β
5import type {
6 UseQueryResult,
7 DefinedUseQueryResult,
8} from '@tanstack/react-query'
9import { QueryClient, useQuery, useQueries } from '@tanstack/react-query'
10import type {
11 PersistedClient,
12 Persister,
13} from '@tanstack/query-persist-client-core'
14import { persistQueryClientSave } from '@tanstack/query-persist-client-core'
15β
16import { createQueryClient, queryKey, sleep } from './utils'
17import { PersistQueryClientProvider } from '../PersistQueryClientProvider'
18β
19const createMockPersister = (): Persister => {
20 let storedState: PersistedClient | undefined
21β
22 return {
23 async persistClient(persistClient: PersistedClient) {
24 storedState = persistClient
25 },
26 async restoreClient() {
27 await sleep(10)
28 return storedState
29 },
30 removeClient() {
31 storedState = undefined
32 },
33 }
34}
35β
36const createMockErrorPersister = (
37 removeClient: Persister['removeClient'],
38): [Error, Persister] => {
39 const error = new Error('restore failed')
40 return [
41 error,
42 {
43 async persistClient() {
44 // noop
45 },
46 async restoreClient() {
47 await sleep(10)
48 throw error
49 },
50 removeClient,
51 },
52 ]
53}
54β
55describe('PersistQueryClientProvider', () => {
56 test('restores cache from persister', async () => {
57 const key = queryKey()
58 const states: UseQueryResult<string>[] = []
59β
60 const queryClient = createQueryClient()
61 await queryClient.prefetchQuery({
62 queryKey: key,
63 queryFn: () => Promise.resolve('hydrated'),
64 })
65β
66 const persister = createMockPersister()
67β
68 await persistQueryClientSave({ queryClient, persister })
69β
70 queryClient.clear()
71β
72 function Page() {
73 const state = useQuery({
74 queryKey: key,
75 queryFn: async () => {
76 await sleep(10)
77 return 'fetched'
78 },
79 })
80β
81 states.push(state)
82β
83 return (
84 <div>
85 <h1>{state.data}</h1>
86 <h2>fetchStatus: {state.fetchStatus}</h2>
87 </div>
88 )
89 }
90β
91 const rendered = render(
92 <PersistQueryClientProvider
93 client={queryClient}
94 persistOptions={{ persister }}
95 >
96 <Page />
97 </PersistQueryClientProvider>,
98 )
99β
100 await waitFor(() => rendered.getByText('fetchStatus: idle'))
101 await waitFor(() => rendered.getByText('hydrated'))
102 await waitFor(() => rendered.getByText('fetched'))
103β
104 expect(states).toHaveLength(4)
105β
106 expect(states[0]).toMatchObject({
107 status: 'pending',
108 fetchStatus: 'idle',
109 data: undefined,
110 })
111β
112 expect(states[1]).toMatchObject({
113 status: 'success',
114 fetchStatus: 'fetching',
115 data: 'hydrated',
116 })
117β
118 expect(states[2]).toMatchObject({
119 status: 'success',
120 fetchStatus: 'fetching',
121 data: 'hydrated',
122 })
123β
124 expect(states[3]).toMatchObject({
125 status: 'success',
126 fetchStatus: 'idle',
127 data: 'fetched',
128 })
129 })
130β
131 test('should also put useQueries into idle state', async () => {
132 const key = queryKey()
133 const states: UseQueryResult[] = []
134β
135 const queryClient = createQueryClient()
136 await queryClient.prefetchQuery({
137 queryKey: key,
138 queryFn: () => Promise.resolve('hydrated'),
139 })
140β
141 const persister = createMockPersister()
142β
143 await persistQueryClientSave({ queryClient, persister })
144β
145 queryClient.clear()
146β
147 function Page() {
148 const [state] = useQueries({
149 queries: [
150 {
151 queryKey: key,
152 queryFn: async (): Promise<string> => {
153 await sleep(10)
154 return 'fetched'
155 },
156 },
157 ],
158 })
159β
160 states.push(state)
161β
162 return (
163 <div>
164 <h1>{state.data}</h1>
165 <h2>fetchStatus: {state.fetchStatus}</h2>
166 </div>
167 )
168 }
169β
170 const rendered = render(
171 <PersistQueryClientProvider
172 client={queryClient}
173 persistOptions={{ persister }}
174 >
175 <Page />
176 </PersistQueryClientProvider>,
177 )
178β
179 await waitFor(() => rendered.getByText('fetchStatus: idle'))
180 await waitFor(() => rendered.getByText('hydrated'))
181 await waitFor(() => rendered.getByText('fetched'))
182β
183 expect(states).toHaveLength(4)
184β
185 expect(states[0]).toMatchObject({
186 status: 'pending',
187 fetchStatus: 'idle',
188 data: undefined,
189 })
190β
191 expect(states[1]).toMatchObject({
192 status: 'success',
193 fetchStatus: 'fetching',
194 data: 'hydrated',
195 })
196β
197 expect(states[2]).toMatchObject({
198 status: 'success',
199 fetchStatus: 'fetching',
200 data: 'hydrated',
201 })
202β
203 expect(states[3]).toMatchObject({
204 status: 'success',
205 fetchStatus: 'idle',
206 data: 'fetched',
207 })
208 })
209β
210 test('should show initialData while restoring', async () => {
211 const key = queryKey()
212 const states: DefinedUseQueryResult<string>[] = []
213β
214 const queryClient = createQueryClient()
215 await queryClient.prefetchQuery({
216 queryKey: key,
217 queryFn: () => Promise.resolve('hydrated'),
218 })
219β
220 const persister = createMockPersister()
221β
222 await persistQueryClientSave({ queryClient, persister })
223β
224 queryClient.clear()
225β
226 function Page() {
227 const state = useQuery({
228 queryKey: key,
229 queryFn: async () => {
230 await sleep(10)
231 return 'fetched'
232 },
233β
234 initialData: 'initial',
235 // make sure that initial data is older than the hydration data
236 // otherwise initialData would be newer and takes precedence
237 initialDataUpdatedAt: 1,
238 })
239β
240 states.push(state)
241β
242 return (
243 <div>
244 <h1>{state.data}</h1>
245 <h2>fetchStatus: {state.fetchStatus}</h2>
246 </div>
247 )
248 }
249β
250 const rendered = render(
251 <PersistQueryClientProvider
252 client={queryClient}
253 persistOptions={{ persister }}
254 >
255 <Page />
256 </PersistQueryClientProvider>,
257 )
258β
259 await waitFor(() => rendered.getByText('initial'))
260 await waitFor(() => rendered.getByText('hydrated'))
261 await waitFor(() => rendered.getByText('fetched'))
262β
263 expect(states).toHaveLength(4)
264β
265 expect(states[0]).toMatchObject({
266 status: 'success',
267 fetchStatus: 'idle',
268 data: 'initial',
269 })
270β
271 expect(states[1]).toMatchObject({
272 status: 'success',
273 fetchStatus: 'fetching',
274 data: 'hydrated',
275 })
276β
277 expect(states[2]).toMatchObject({
278 status: 'success',
279 fetchStatus: 'fetching',
280 data: 'hydrated',
281 })
282β
283 expect(states[3]).toMatchObject({
284 status: 'success',
285 fetchStatus: 'idle',
286 data: 'fetched',
287 })
288 })
289β
290 test('should not refetch after restoring when data is fresh', async () => {
291 const key = queryKey()
292 const states: UseQueryResult<string>[] = []
293β
294 const queryClient = createQueryClient()
295 await queryClient.prefetchQuery({
296 queryKey: key,
297 queryFn: () => Promise.resolve('hydrated'),
298 })
299β
300 const persister = createMockPersister()
301β
302 await persistQueryClientSave({ queryClient, persister })
303β
304 queryClient.clear()
305β
306 let fetched = false
307β
308 function Page() {
309 const state = useQuery({
310 queryKey: key,
311 queryFn: async () => {
312 fetched = true
313 await sleep(10)
314 return 'fetched'
315 },
316β
317 staleTime: Infinity,
318 })
319β
320 states.push(state)
321β
322 return (
323 <div>
324 <h1>data: {state.data ?? 'null'}</h1>
325 <h2>fetchStatus: {state.fetchStatus}</h2>
326 </div>
327 )
328 }
329β
330 const rendered = render(
331 <PersistQueryClientProvider
332 client={queryClient}
333 persistOptions={{ persister }}
334 >
335 <Page />
336 </PersistQueryClientProvider>,
337 )
338β
339 await waitFor(() => rendered.getByText('data: null'))
340 await waitFor(() => rendered.getByText('data: hydrated'))
341β
342 expect(states).toHaveLength(3)
343β
344 expect(fetched).toBe(false)
345β
346 expect(states[0]).toMatchObject({
347 status: 'pending',
348 fetchStatus: 'idle',
349 data: undefined,
350 })
351β
352 expect(states[1]).toMatchObject({
353 status: 'success',
354 fetchStatus: 'idle',
355 data: 'hydrated',
356 })
357β
358 // #5443 seems like we get an extra render now ...
359 expect(states[1]).toStrictEqual(states[2])
360 })
361β
362 test('should call onSuccess after successful restoring', async () => {
363 const key = queryKey()
364β
365 const queryClient = createQueryClient()
366 await queryClient.prefetchQuery({
367 queryKey: key,
368 queryFn: () => Promise.resolve('hydrated'),
369 })
370β
371 const persister = createMockPersister()
372β
373 await persistQueryClientSave({ queryClient, persister })
374β
375 queryClient.clear()
376β
377 function Page() {
378 const state = useQuery({
379 queryKey: key,
380 queryFn: async () => {
381 await sleep(10)
382 return 'fetched'
383 },
384 })
385β
386 return (
387 <div>
388 <h1>{state.data}</h1>
389 <h2>fetchStatus: {state.fetchStatus}</h2>
390 </div>
391 )
392 }
393β
394 const onSuccess = vi.fn()
395β
396 const rendered = render(
397 <PersistQueryClientProvider
398 client={queryClient}
399 persistOptions={{ persister }}
400 onSuccess={onSuccess}
401 >
402 <Page />
403 </PersistQueryClientProvider>,
404 )
405 expect(onSuccess).toHaveBeenCalledTimes(0)
406β
407 await waitFor(() => rendered.getByText('hydrated'))
408 expect(onSuccess).toHaveBeenCalledTimes(1)
409 await waitFor(() => rendered.getByText('fetched'))
410 })
411β
412 test('should await onSuccess after successful restoring', async () => {
413 const key = queryKey()
414β
415 const queryClient = createQueryClient()
416 await queryClient.prefetchQuery({
417 queryKey: key,
418 queryFn: () => Promise.resolve('hydrated'),
419 })
420β
421 const persister = createMockPersister()
422β
423 await persistQueryClientSave({ queryClient, persister })
424β
425 queryClient.clear()
426β
427 const states: Array<string> = []
428β
429 function Page() {
430 const { data, fetchStatus } = useQuery({
431 queryKey: key,
432 queryFn: async () => {
433 states.push('fetching')
434 await sleep(10)
435 states.push('fetched')
436 return 'fetched'
437 },
438 })
439β
440 return (
441 <div>
442 <h1>{data}</h1>
443 <h2>fetchStatus: {fetchStatus}</h2>
444 </div>
445 )
446 }
447β
448 const rendered = render(
449 <PersistQueryClientProvider
450 client={queryClient}
451 persistOptions={{ persister }}
452 onSuccess={async () => {
453 states.push('onSuccess')
454 await sleep(20)
455 states.push('onSuccess done')
456 }}
457 >
458 <Page />
459 </PersistQueryClientProvider>,
460 )
461β
462 await waitFor(() => rendered.getByText('hydrated'))
463 await waitFor(() => rendered.getByText('fetched'))
464 expect(states).toEqual([
465 'onSuccess',
466 'onSuccess done',
467 'fetching',
468 'fetched',
469 ])
470 })
471β
472 test('should remove cache after non-successful restoring', async () => {
473 const key = queryKey()
474 const consoleMock = vi.spyOn(console, 'error')
475 const consoleWarn = vi
476 .spyOn(console, 'warn')
477 .mockImplementation(() => undefined)
478 consoleMock.mockImplementation(() => undefined)
479β
480 const queryClient = createQueryClient()
481 const removeClient = vi.fn()
482β
483 const [error, persister] = createMockErrorPersister(removeClient)
484β
485 function Page() {
486 const state = useQuery({
487 queryKey: key,
488 queryFn: async () => {
489 await sleep(10)
490 return 'fetched'
491 },
492 })
493β
494 return (
495 <div>
496 <h1>{state.data}</h1>
497 <h2>fetchStatus: {state.fetchStatus}</h2>
498 </div>
499 )
500 }
501β
502 const rendered = render(
503 <PersistQueryClientProvider
504 client={queryClient}
505 persistOptions={{ persister }}
506 >
507 <Page />
508 </PersistQueryClientProvider>,
509 )
510β
511 await waitFor(() => rendered.getByText('fetched'))
512 expect(removeClient).toHaveBeenCalledTimes(1)
513 expect(consoleMock).toHaveBeenCalledTimes(1)
514 expect(consoleMock).toHaveBeenNthCalledWith(1, error)
515 consoleMock.mockRestore()
516 consoleWarn.mockRestore()
517 })
518β
519 test('should be able to persist into multiple clients', async () => {
520 const key = queryKey()
521 const states: UseQueryResult[] = []
522β
523 const queryClient = createQueryClient()
524 await queryClient.prefetchQuery({
525 queryKey: key,
526 queryFn: () => Promise.resolve('hydrated'),
527 })
528β
529 const persister = createMockPersister()
530β
531 await persistQueryClientSave({ queryClient, persister })
532β
533 queryClient.clear()
534β
535 const onSuccess = vi.fn()
536β
537 const queryFn1 = vi.fn().mockImplementation(async () => {
538 await sleep(10)
539 return 'queryFn1'
540 })
541 const queryFn2 = vi.fn().mockImplementation(async () => {
542 await sleep(10)
543 return 'queryFn2'
544 })
545β
546 function App() {
547 const [client, setClient] = React.useState(
548 () =>
549 new QueryClient({
550 defaultOptions: {
551 queries: {
552 queryFn: queryFn1,
553 },
554 },
555 }),
556 )
557β
558 React.useEffect(() => {
559 setClient(
560 new QueryClient({
561 defaultOptions: {
562 queries: {
563 queryFn: queryFn2,
564 },
565 },
566 }),
567 )
568 }, [])
569β
570 return (
571 <PersistQueryClientProvider
572 client={client}
573 persistOptions={{ persister }}
574 onSuccess={onSuccess}
575 >
576 <Page />
577 </PersistQueryClientProvider>
578 )
579 }
580β
581 function Page() {
582 const state = useQuery({ queryKey: key })
583β
584 states.push(state)
585β
586 return (
587 <div>
588 <h1>{String(state.data)}</h1>
589 <h2>fetchStatus: {state.fetchStatus}</h2>
590 </div>
591 )
592 }
593β
594 const rendered = render(<App />)
595β
596 await waitFor(() => rendered.getByText('hydrated'))
597 await waitFor(() => rendered.getByText('queryFn2'))
598β
599 expect(queryFn1).toHaveBeenCalledTimes(0)
600 expect(queryFn2).toHaveBeenCalledTimes(1)
601 expect(onSuccess).toHaveBeenCalledTimes(1)
602β
603 expect(states).toHaveLength(5)
604β
605 expect(states[0]).toMatchObject({
606 status: 'pending',
607 fetchStatus: 'idle',
608 data: undefined,
609 })
610β
611 expect(states[1]).toMatchObject({
612 status: 'pending',
613 fetchStatus: 'idle',
614 data: undefined,
615 })
616β
617 expect(states[2]).toMatchObject({
618 status: 'success',
619 fetchStatus: 'fetching',
620 data: 'hydrated',
621 })
622β
623 expect(states[3]).toMatchObject({
624 status: 'success',
625 fetchStatus: 'fetching',
626 data: 'hydrated',
627 })
628β
629 expect(states[4]).toMatchObject({
630 status: 'success',
631 fetchStatus: 'idle',
632 data: 'queryFn2',
633 })
634 })
635})