Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

PersistQueryClientProvider.test.tsx

431 lines11.8 KB

1// Ported to the 2.0-native read layer: `data` is an async computation, so a
2// query with nothing cached suspends into <Loading> for the whole restore
3// window instead of rendering a pending snapshot. These tests assert the
4// user-visible transitions (fallback -> restored value -> refreshed value)
5// and the fetch/callback bookkeeping around them; the pre-rewrite suite
6// snapshotted observer result objects on every notification, which the
7// rewrite no longer produces.
8import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
9import { render, screen } from '@solidjs/testing-library'
10import { QueryClient, noop, useQueries, useQuery } from '@tanstack/solid-query'
11import { persistQueryClientSave } from '@tanstack/query-persist-client-core'
12import { Loading, createSignal } from 'solid-js'
13import { createKey, sleep } from '@tanstack/query-test-utils'
14import { PersistQueryClientProvider } from '../PersistQueryClientProvider'
15import type {
16 PersistedClient,
17 Persister,
18 Promisable,
19} from '@tanstack/query-persist-client-core'
20​
21const createMockPersister = (): Persister => {
22 let storedState: PersistedClient | undefined
23​
24 return {
25 persistClient(persistClient: PersistedClient) {
26 storedState = persistClient
27 },
28 async restoreClient() {
29 return sleep(10).then(() => storedState)
30 },
31 removeClient() {
32 storedState = undefined
33 },
34 }
36​
37const createMockErrorPersister = (
38 removeClient: Persister['removeClient'],
39): [Error, Persister] => {
40 const error = new Error('restore failed')
41 return [
42 error,
43 {
44 async persistClient() {
45 // noop
46 },
47 async restoreClient() {
48 await sleep(10)
49 throw error
50 },
51 removeClient,
52 },
53 ]
55​
56/**
57 * Seeds a persister with a settled `'hydrated'` entry for `key` and hands
58 * back an empty client to restore it into.
59 */
60async function setup() {
61 const key = createKey()
62​
63 const queryClient = new QueryClient()
64 void queryClient
65 .query({
66 queryKey: key,
67 queryFn: () => sleep(10).then(() => 'hydrated'),
68 })
69 .catch(noop)
70 await vi.advanceTimersByTimeAsync(10)
71​
72 const persister = createMockPersister()
73​
74 persistQueryClientSave({ queryClient, persister })
75 await vi.advanceTimersByTimeAsync(0)
76​
77 queryClient.clear()
78​
79 return { key, queryClient, persister }
81​
82describe('PersistQueryClientProvider', () => {
83 beforeEach(() => {
84 vi.useFakeTimers()
85 })
86​
87 afterEach(() => {
88 vi.useRealTimers()
89 })
90​
91 it('restores cache from persister', async () => {
92 const { key, queryClient, persister } = await setup()
93​
94 const queryFn = vi.fn<() => Promise<string>>(() =>
95 sleep(10).then(() => 'fetched'),
96 )
97​
98 function Page() {
99 const state = useQuery(() => ({ queryKey: key, queryFn }))
100​
101 return (
102 <div>
103 <h1>{state.data}</h1>
104 <h2>fetchStatus: {state.fetchStatus}</h2>
105 </div>
106 )
107 }
108​
109 render(() => (
110 <Loading fallback={<span>loading</span>}>
111 <PersistQueryClientProvider
112 client={queryClient}
113 persistOptions={{ persister }}
114 >
115 <Page />
116 </PersistQueryClientProvider>
117 </Loading>
118 ))
119​
120 // Nothing is cached yet and no fetch may start while restoring, so the
121 // read has nothing to settle on and the boundary holds.
122 expect(screen.getByText('loading')).toBeInTheDocument()
123 expect(queryFn).toHaveBeenCalledTimes(0)
124​
125 // The restored entry lands, the boundary resolves, and the now-stale
126 // query refetches in the background.
127 await vi.advanceTimersByTimeAsync(10)
128 expect(screen.getByText('hydrated')).toBeInTheDocument()
129​
130 await vi.advanceTimersByTimeAsync(10)
131 expect(screen.getByText('fetched')).toBeInTheDocument()
132 expect(screen.getByText('fetchStatus: idle')).toBeInTheDocument()
133 })
134​
135 it('should also put useQueries into idle state', async () => {
136 const { key, queryClient, persister } = await setup()
137​
138 const queryFn = vi.fn<() => Promise<string>>(() =>
139 sleep(10).then(() => 'fetched'),
140 )
141​
142 function Page() {
143 const queries = useQueries(() => ({
144 queries: [{ queryKey: key, queryFn }],
145 }))
146​
147 return (
148 <div>
149 <h1>{queries[0].data}</h1>
150 <h2>fetchStatus: {queries[0].fetchStatus}</h2>
151 </div>
152 )
153 }
154​
155 render(() => (
156 <Loading fallback={<span>loading</span>}>
157 <PersistQueryClientProvider
158 client={queryClient}
159 persistOptions={{ persister }}
160 >
161 <Page />
162 </PersistQueryClientProvider>
163 </Loading>
164 ))
165​
166 expect(screen.getByText('loading')).toBeInTheDocument()
167 expect(queryFn).toHaveBeenCalledTimes(0)
168​
169 await vi.advanceTimersByTimeAsync(10)
170 expect(screen.getByText('hydrated')).toBeInTheDocument()
171​
172 await vi.advanceTimersByTimeAsync(10)
173 expect(screen.getByText('fetched')).toBeInTheDocument()
174 expect(screen.getByText('fetchStatus: idle')).toBeInTheDocument()
175 })
176​
177 it('should show initialData while restoring', async () => {
178 const { key, queryClient, persister } = await setup()
179​
180 function Page() {
181 const state = useQuery(() => ({
182 queryKey: key,
183 queryFn: () => sleep(10).then(() => 'fetched'),
184 initialData: 'initial',
185 // make sure that initial data is older than the hydration data
186 // otherwise initialData would be newer and takes precedence
187 initialDataUpdatedAt: 1,
188 }))
189​
190 return (
191 <div>
192 <h1>{state.data}</h1>
193 <h2>fetchStatus: {state.fetchStatus}</h2>
194 </div>
195 )
196 }
197​
198 render(() => (
199 <Loading fallback={<span>loading</span>}>
200 <PersistQueryClientProvider
201 client={queryClient}
202 persistOptions={{ persister }}
203 >
204 <Page />
205 </PersistQueryClientProvider>
206 </Loading>
207 ))
208​
209 // `initialData` settles the read synchronously, so the boundary never
210 // falls back β€” this is the one restore path that renders content at t=0.
211 expect(screen.getByText('initial')).toBeInTheDocument()
212​
213 await vi.advanceTimersByTimeAsync(10)
214 expect(screen.getByText('hydrated')).toBeInTheDocument()
215​
216 await vi.advanceTimersByTimeAsync(10)
217 expect(screen.getByText('fetched')).toBeInTheDocument()
218 })
219​
220 it('should not refetch after restoring when data is fresh', async () => {
221 const { key, queryClient, persister } = await setup()
222​
223 let fetched = false
224​
225 function Page() {
226 const state = useQuery(() => ({
227 queryKey: key,
228 queryFn: () =>
229 sleep(10).then(() => {
230 fetched = true
231 return 'fetched'
232 }),
233 staleTime: Infinity,
234 }))
235​
236 return (
237 <div>
238 <h1>data: {state.data}</h1>
239 <h2>fetchStatus: {state.fetchStatus}</h2>
240 </div>
241 )
242 }
243​
244 render(() => (
245 <Loading fallback={<span>loading</span>}>
246 <PersistQueryClientProvider
247 client={queryClient}
248 persistOptions={{ persister }}
249 >
250 <Page />
251 </PersistQueryClientProvider>
252 </Loading>
253 ))
254​
255 expect(screen.getByText('loading')).toBeInTheDocument()
256​
257 await vi.advanceTimersByTimeAsync(10)
258 expect(screen.getByText('data: hydrated')).toBeInTheDocument()
259​
260 // Restored data is fresh forever, so the mount policy leaves it alone.
261 await vi.advanceTimersByTimeAsync(10)
262 expect(screen.getByText('data: hydrated')).toBeInTheDocument()
263 expect(screen.getByText('fetchStatus: idle')).toBeInTheDocument()
264 expect(fetched).toBe(false)
265 })
266​
267 it('should call onSuccess after successful restoring', async () => {
268 const { key, queryClient, persister } = await setup()
269​
270 function Page() {
271 const state = useQuery(() => ({
272 queryKey: key,
273 queryFn: () => sleep(10).then(() => 'fetched'),
274 }))
275​
276 return (
277 <div>
278 <h1>{state.data}</h1>
279 <h2>fetchStatus: {state.fetchStatus}</h2>
280 </div>
281 )
282 }
283​
284 const onSuccess = vi.fn<() => void>()
285​
286 render(() => (
287 <Loading>
288 <PersistQueryClientProvider
289 client={queryClient}
290 persistOptions={{ persister }}
291 onSuccess={onSuccess}
292 >
293 <Page />
294 </PersistQueryClientProvider>
295 </Loading>
296 ))
297​
298 expect(onSuccess).toHaveBeenCalledTimes(0)
299 await vi.advanceTimersByTimeAsync(10)
300 expect(screen.getByText('hydrated')).toBeInTheDocument()
301 expect(onSuccess).toHaveBeenCalledTimes(1)
302 await vi.advanceTimersByTimeAsync(10)
303 expect(screen.getByText('fetched')).toBeInTheDocument()
304 })
305​
306 it('should remove cache after non-successful restoring', async () => {
307 const key = createKey()
308​
309 const consoleErrorMock = vi
310 .spyOn(console, 'error')
311 .mockReturnValue(undefined)
312 const queryClient = new QueryClient()
313 const removeClient = vi.fn<() => Promisable<void>>()
314 const onSuccess = vi.fn<() => void>()
315 const onError = vi.fn<() => void>()
316​
317 const [error, persister] = createMockErrorPersister(removeClient)
318​
319 function Page() {
320 const state = useQuery(() => ({
321 queryKey: key,
322 queryFn: () => sleep(10).then(() => 'fetched'),
323 }))
324​
325 return (
326 <div>
327 <h1>{state.data}</h1>
328 <h2>fetchStatus: {state.fetchStatus}</h2>
329 </div>
330 )
331 }
332​
333 render(() => (
334 <Loading>
335 <PersistQueryClientProvider
336 client={queryClient}
337 persistOptions={{ persister }}
338 onSuccess={onSuccess}
339 onError={onError}
340 >
341 <Page />
342 </PersistQueryClientProvider>
343 </Loading>
344 ))
345​
346 await vi.advanceTimersByTimeAsync(10)
347 expect(removeClient).toHaveBeenCalledTimes(1)
348 expect(onSuccess).toHaveBeenCalledTimes(0)
349 expect(onError).toHaveBeenCalledTimes(1)
350 await vi.advanceTimersByTimeAsync(10)
351 expect(screen.getByText('fetched')).toBeInTheDocument()
352​
353 expect(consoleErrorMock).toHaveBeenCalledTimes(1)
354 expect(consoleErrorMock).toHaveBeenNthCalledWith(1, error)
355 })
356​
357 it('should be able to persist into multiple clients', async () => {
358 const { key, persister } = await setup()
359​
360 const onSuccess = vi.fn<() => void>()
361​
362 const queryFn1 = vi.fn<() => Promise<string>>(() =>
363 sleep(10).then(() => 'queryFn1'),
364 )
365 const queryFn2 = vi.fn<() => Promise<string>>(() =>
366 sleep(10).then(() => 'queryFn2'),
367 )
368​
369 function App() {
370 const [client, setClient] = createSignal(
371 new QueryClient({
372 defaultOptions: {
373 queries: {
374 queryFn: queryFn1,
375 },
376 },
377 }),
378 )
379​
380 queueMicrotask(() => {
381 setClient(
382 new QueryClient({
383 defaultOptions: {
384 queries: {
385 queryFn: queryFn2,
386 },
387 },
388 }),
389 )
390 })
391​
392 return (
393 <PersistQueryClientProvider
394 client={client()}
395 persistOptions={{ persister }}
396 onSuccess={onSuccess}
397 >
398 <Page />
399 </PersistQueryClientProvider>
400 )
401 }
402​
403 function Page() {
404 const state = useQuery(() => ({ queryKey: key }))
405​
406 return (
407 <div>
408 <h1>{String(state.data)}</h1>
409 <h2>fetchStatus: {state.fetchStatus}</h2>
410 </div>
411 )
412 }
413​
414 render(() => (
415 <Loading fallback={<span>loading</span>}>
416 <App />
417 </Loading>
418 ))
419​
420 // The read follows the reactive client accessor, so it is already
421 // pointed at the second client before the restore lands. The restore
422 // still runs exactly once, against the client the provider started
423 // with, so the swapped-in client fetches its own value.
424 await vi.advanceTimersByTimeAsync(20)
425 expect(screen.getByText('queryFn2')).toBeInTheDocument()
426 expect(screen.getByText('fetchStatus: idle')).toBeInTheDocument()
427​
428 expect(queryFn1).toHaveBeenCalledTimes(0)
429 expect(onSuccess).toHaveBeenCalledTimes(1)
430 })
431})