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