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 function Page() {
307 const state = useQuery({
308 queryKey: key,
309 queryFn: async () => {
310 await sleep(10)
311 return 'fetched'
312 },
313β
314 staleTime: Infinity,
315 })
316β
317 states.push(state)
318β
319 return (
320 <div>
321 <h1>data: {state.data ?? 'null'}</h1>
322 <h2>fetchStatus: {state.fetchStatus}</h2>
323 </div>
324 )
325 }
326β
327 const rendered = render(
328 <PersistQueryClientProvider
329 client={queryClient}
330 persistOptions={{ persister }}
331 >
332 <Page />
333 </PersistQueryClientProvider>,
334 )
335β
336 await waitFor(() => rendered.getByText('data: null'))
337 await waitFor(() => rendered.getByText('data: hydrated'))
338β
339 expect(states).toHaveLength(2)
340β
341 expect(states[0]).toMatchObject({
342 status: 'pending',
343 fetchStatus: 'idle',
344 data: undefined,
345 })
346β
347 expect(states[1]).toMatchObject({
348 status: 'success',
349 fetchStatus: 'idle',
350 data: 'hydrated',
351 })
352 })
353β
354 test('should call onSuccess after successful restoring', async () => {
355 const key = queryKey()
356β
357 const queryClient = createQueryClient()
358 await queryClient.prefetchQuery({
359 queryKey: key,
360 queryFn: () => Promise.resolve('hydrated'),
361 })
362β
363 const persister = createMockPersister()
364β
365 await persistQueryClientSave({ queryClient, persister })
366β
367 queryClient.clear()
368β
369 function Page() {
370 const state = useQuery({
371 queryKey: key,
372 queryFn: async () => {
373 await sleep(10)
374 return 'fetched'
375 },
376 })
377β
378 return (
379 <div>
380 <h1>{state.data}</h1>
381 <h2>fetchStatus: {state.fetchStatus}</h2>
382 </div>
383 )
384 }
385β
386 const onSuccess = vi.fn()
387β
388 const rendered = render(
389 <PersistQueryClientProvider
390 client={queryClient}
391 persistOptions={{ persister }}
392 onSuccess={onSuccess}
393 >
394 <Page />
395 </PersistQueryClientProvider>,
396 )
397 expect(onSuccess).toHaveBeenCalledTimes(0)
398β
399 await waitFor(() => rendered.getByText('hydrated'))
400 expect(onSuccess).toHaveBeenCalledTimes(1)
401 await waitFor(() => rendered.getByText('fetched'))
402 })
403β
404 test('should await onSuccess after successful restoring', async () => {
405 const key = queryKey()
406β
407 const queryClient = createQueryClient()
408 await queryClient.prefetchQuery({
409 queryKey: key,
410 queryFn: () => Promise.resolve('hydrated'),
411 })
412β
413 const persister = createMockPersister()
414β
415 await persistQueryClientSave({ queryClient, persister })
416β
417 queryClient.clear()
418β
419 const states: Array<string> = []
420β
421 function Page() {
422 const { data, fetchStatus } = useQuery({
423 queryKey: key,
424 queryFn: async () => {
425 states.push('fetching')
426 await sleep(10)
427 states.push('fetched')
428 return 'fetched'
429 },
430 })
431β
432 return (
433 <div>
434 <h1>{data}</h1>
435 <h2>fetchStatus: {fetchStatus}</h2>
436 </div>
437 )
438 }
439β
440 const rendered = render(
441 <PersistQueryClientProvider
442 client={queryClient}
443 persistOptions={{ persister }}
444 onSuccess={async () => {
445 states.push('onSuccess')
446 await sleep(20)
447 states.push('onSuccess done')
448 }}
449 >
450 <Page />
451 </PersistQueryClientProvider>,
452 )
453β
454 await waitFor(() => rendered.getByText('hydrated'))
455 await waitFor(() => rendered.getByText('fetched'))
456 expect(states).toEqual([
457 'onSuccess',
458 'onSuccess done',
459 'fetching',
460 'fetched',
461 ])
462 })
463β
464 test('should remove cache after non-successful restoring', async () => {
465 const key = queryKey()
466 const consoleMock = vi.spyOn(console, 'error')
467 const consoleWarn = vi
468 .spyOn(console, 'warn')
469 .mockImplementation(() => undefined)
470 consoleMock.mockImplementation(() => undefined)
471β
472 const queryClient = createQueryClient()
473 const removeClient = vi.fn()
474β
475 const [error, persister] = createMockErrorPersister(removeClient)
476β
477 function Page() {
478 const state = useQuery({
479 queryKey: key,
480 queryFn: async () => {
481 await sleep(10)
482 return 'fetched'
483 },
484 })
485β
486 return (
487 <div>
488 <h1>{state.data}</h1>
489 <h2>fetchStatus: {state.fetchStatus}</h2>
490 </div>
491 )
492 }
493β
494 const rendered = render(
495 <PersistQueryClientProvider
496 client={queryClient}
497 persistOptions={{ persister }}
498 >
499 <Page />
500 </PersistQueryClientProvider>,
501 )
502β
503 await waitFor(() => rendered.getByText('fetched'))
504 expect(removeClient).toHaveBeenCalledTimes(1)
505 expect(consoleMock).toHaveBeenCalledTimes(1)
506 expect(consoleMock).toHaveBeenNthCalledWith(1, error)
507 consoleMock.mockRestore()
508 consoleWarn.mockRestore()
509 })
510β
511 test('should be able to persist into multiple clients', async () => {
512 const key = queryKey()
513 const states: UseQueryResult[] = []
514β
515 const queryClient = createQueryClient()
516 await queryClient.prefetchQuery({
517 queryKey: key,
518 queryFn: () => Promise.resolve('hydrated'),
519 })
520β
521 const persister = createMockPersister()
522β
523 await persistQueryClientSave({ queryClient, persister })
524β
525 queryClient.clear()
526β
527 const onSuccess = vi.fn()
528β
529 const queryFn1 = vi.fn().mockImplementation(async () => {
530 await sleep(10)
531 return 'queryFn1'
532 })
533 const queryFn2 = vi.fn().mockImplementation(async () => {
534 await sleep(10)
535 return 'queryFn2'
536 })
537β
538 function App() {
539 const [client, setClient] = React.useState(
540 () =>
541 new QueryClient({
542 defaultOptions: {
543 queries: {
544 queryFn: queryFn1,
545 },
546 },
547 }),
548 )
549β
550 React.useEffect(() => {
551 setClient(
552 new QueryClient({
553 defaultOptions: {
554 queries: {
555 queryFn: queryFn2,
556 },
557 },
558 }),
559 )
560 }, [])
561β
562 return (
563 <PersistQueryClientProvider
564 client={client}
565 persistOptions={{ persister }}
566 onSuccess={onSuccess}
567 >
568 <Page />
569 </PersistQueryClientProvider>
570 )
571 }
572β
573 function Page() {
574 const state = useQuery({ queryKey: key })
575β
576 states.push(state)
577β
578 return (
579 <div>
580 <h1>{String(state.data)}</h1>
581 <h2>fetchStatus: {state.fetchStatus}</h2>
582 </div>
583 )
584 }
585β
586 const rendered = render(<App />)
587β
588 await waitFor(() => rendered.getByText('hydrated'))
589 await waitFor(() => rendered.getByText('queryFn2'))
590β
591 expect(queryFn1).toHaveBeenCalledTimes(0)
592 expect(queryFn2).toHaveBeenCalledTimes(1)
593 expect(onSuccess).toHaveBeenCalledTimes(1)
594β
595 expect(states).toHaveLength(5)
596β
597 expect(states[0]).toMatchObject({
598 status: 'pending',
599 fetchStatus: 'idle',
600 data: undefined,
601 })
602β
603 expect(states[1]).toMatchObject({
604 status: 'pending',
605 fetchStatus: 'idle',
606 data: undefined,
607 })
608β
609 expect(states[2]).toMatchObject({
610 status: 'success',
611 fetchStatus: 'fetching',
612 data: 'hydrated',
613 })
614β
615 expect(states[3]).toMatchObject({
616 status: 'success',
617 fetchStatus: 'fetching',
618 data: 'hydrated',
619 })
620β
621 expect(states[4]).toMatchObject({
622 status: 'success',
623 fetchStatus: 'idle',
624 data: 'queryFn2',
625 })
626 })
627})