Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 QueryClient,
4 injectQuery,
5 noop,
6 provideTanStackQuery,
7} from '@tanstack/angular-query-experimental'
8import { persistQueryClientSave } from '@tanstack/query-persist-client-core'
9import {
10 Component,
11 effect,
12 provideZonelessChangeDetection,
13} from '@angular/core'
14import { render } from '@testing-library/angular'
15import { createKey, sleep } from '@tanstack/query-test-utils'
16import { withPersistQueryClient } from '../with-persist-query-client'
17import type {
18 PersistedClient,
19 Persister,
20 Promisable,
21} from '@tanstack/query-persist-client-core'
22β
23const createMockPersister = (): Persister => {
24 let storedState: PersistedClient | undefined
25β
26 return {
27 persistClient(persistClient: PersistedClient) {
28 storedState = persistClient
29 },
30 async restoreClient() {
31 return sleep(10).then(() => storedState)
32 },
33 removeClient() {
34 storedState = undefined
35 },
36 }
37}
38β
39const createMockErrorPersister = (
40 removeClient: Persister['removeClient'],
41): [Error, Persister] => {
42 const error = new Error('restore failed')
43 return [
44 error,
45 {
46 async persistClient() {
47 // noop
48 },
49 async restoreClient() {
50 await sleep(10)
51 throw error
52 },
53 removeClient,
54 },
55 ]
56}
57β
58describe('withPersistQueryClient', () => {
59 beforeEach(() => {
60 vi.useFakeTimers()
61 })
62β
63 afterEach(() => {
64 vi.useRealTimers()
65 })
66β
67 it('should restore cache from persister', async () => {
68 const key = createKey()
69 const states: Array<{
70 status: string
71 fetchStatus: string
72 data: string | undefined
73 }> = []
74β
75 const queryClient = new QueryClient()
76 void queryClient
77 .query({
78 queryKey: key,
79 queryFn: () => sleep(10).then(() => 'hydrated'),
80 })
81 .catch(noop)
82 await vi.advanceTimersByTimeAsync(10)
83β
84 const persister = createMockPersister()
85β
86 persistQueryClientSave({ queryClient, persister })
87 await vi.advanceTimersByTimeAsync(0)
88β
89 queryClient.clear()
90β
91 @Component({
92 template: `
93 <div>
94 <h1>{{ state.data() }}</h1>
95 <h2>fetchStatus: {{ state.fetchStatus() }}</h2>
96 </div>
97 `,
98 })
99 class Page {
100 state = injectQuery(() => ({
101 queryKey: key,
102 queryFn: () => sleep(10).then(() => 'fetched'),
103 }))
104β
105 constructor() {
106 effect(() => {
107 states.push({
108 status: this.state.status(),
109 fetchStatus: this.state.fetchStatus(),
110 data: this.state.data(),
111 })
112 })
113 }
114 }
115β
116 const rendered = await render(Page, {
117 providers: [
118 provideZonelessChangeDetection(),
119 provideTanStackQuery(
120 queryClient,
121 withPersistQueryClient({ persistOptions: { persister } }),
122 ),
123 ],
124 })
125β
126 expect(rendered.getByText('fetchStatus: idle')).toBeInTheDocument()
127 await vi.advanceTimersByTimeAsync(10)
128 rendered.fixture.detectChanges()
129 expect(rendered.getByText('hydrated')).toBeInTheDocument()
130 await vi.advanceTimersByTimeAsync(11)
131 rendered.fixture.detectChanges()
132 expect(rendered.getByText('fetched')).toBeInTheDocument()
133β
134 expect(states).toHaveLength(3)
135β
136 expect(states[0]).toMatchObject({
137 status: 'pending',
138 fetchStatus: 'idle',
139 data: undefined,
140 })
141β
142 expect(states[1]).toMatchObject({
143 status: 'success',
144 fetchStatus: 'fetching',
145 data: 'hydrated',
146 })
147β
148 expect(states[2]).toMatchObject({
149 status: 'success',
150 fetchStatus: 'idle',
151 data: 'fetched',
152 })
153 })
154β
155 it.todo(
156 'should transition injectQueries to an idle state (once injectQueries is functional)',
157 )
158β
159 it('should show initialData while restoring', async () => {
160 const key = createKey()
161 const states: Array<{
162 status: string
163 fetchStatus: string
164 data: string | undefined
165 }> = []
166β
167 const queryClient = new QueryClient()
168 void queryClient
169 .query({
170 queryKey: key,
171 queryFn: () => sleep(10).then(() => 'hydrated'),
172 })
173 .catch(noop)
174 await vi.advanceTimersByTimeAsync(10)
175β
176 const persister = createMockPersister()
177β
178 persistQueryClientSave({ queryClient, persister })
179 await vi.advanceTimersByTimeAsync(0)
180β
181 queryClient.clear()
182β
183 @Component({
184 template: `
185 <div>
186 <h1>{{ state.data() }}</h1>
187 <h2>fetchStatus: {{ state.fetchStatus() }}</h2>
188 </div>
189 `,
190 })
191 class Page {
192 state = injectQuery(() => ({
193 queryKey: key,
194 queryFn: () => sleep(10).then(() => 'fetched'),
195 initialData: 'initial',
196 // make sure that initial data is older than the hydration data
197 // otherwise initialData would be newer and takes precedence
198 initialDataUpdatedAt: 1,
199 }))
200β
201 constructor() {
202 effect(() => {
203 states.push({
204 status: this.state.status(),
205 fetchStatus: this.state.fetchStatus(),
206 data: this.state.data(),
207 })
208 })
209 }
210 }
211β
212 const rendered = await render(Page, {
213 providers: [
214 provideZonelessChangeDetection(),
215 provideTanStackQuery(
216 queryClient,
217 withPersistQueryClient({ persistOptions: { persister } }),
218 ),
219 ],
220 })
221β
222 expect(rendered.getByText('initial')).toBeInTheDocument()
223 await vi.advanceTimersByTimeAsync(10)
224 rendered.fixture.detectChanges()
225 expect(rendered.getByText('hydrated')).toBeInTheDocument()
226 await vi.advanceTimersByTimeAsync(11)
227 rendered.fixture.detectChanges()
228 expect(rendered.getByText('fetched')).toBeInTheDocument()
229β
230 expect(states).toHaveLength(3)
231β
232 expect(states[0]).toMatchObject({
233 status: 'success',
234 fetchStatus: 'idle',
235 data: 'initial',
236 })
237β
238 expect(states[1]).toMatchObject({
239 status: 'success',
240 fetchStatus: 'fetching',
241 data: 'hydrated',
242 })
243β
244 expect(states[2]).toMatchObject({
245 status: 'success',
246 fetchStatus: 'idle',
247 data: 'fetched',
248 })
249 })
250β
251 it('should not refetch after restoring when data is fresh', async () => {
252 const key = createKey()
253 const states: Array<{
254 status: string
255 fetchStatus: string
256 data: string | undefined
257 }> = []
258β
259 const queryClient = new QueryClient()
260 void queryClient
261 .query({
262 queryKey: key,
263 queryFn: () => sleep(10).then(() => 'hydrated'),
264 })
265 .catch(noop)
266 await vi.advanceTimersByTimeAsync(10)
267β
268 const persister = createMockPersister()
269β
270 persistQueryClientSave({ queryClient, persister })
271 await vi.advanceTimersByTimeAsync(0)
272β
273 queryClient.clear()
274β
275 let fetched = false
276β
277 @Component({
278 template: `
279 <div>
280 <h1>data: {{ state.data() ?? 'null' }}</h1>
281 <h2>fetchStatus: {{ state.fetchStatus() }}</h2>
282 </div>
283 `,
284 })
285 class Page {
286 state = injectQuery(() => ({
287 queryKey: key,
288 queryFn: () =>
289 sleep(10).then(() => {
290 fetched = true
291 return 'fetched'
292 }),
293 staleTime: Infinity,
294 }))
295β
296 constructor() {
297 effect(() => {
298 states.push({
299 status: this.state.status(),
300 fetchStatus: this.state.fetchStatus(),
301 data: this.state.data(),
302 })
303 })
304 }
305 }
306β
307 const rendered = await render(Page, {
308 providers: [
309 provideZonelessChangeDetection(),
310 provideTanStackQuery(
311 queryClient,
312 withPersistQueryClient({ persistOptions: { persister } }),
313 ),
314 ],
315 })
316β
317 expect(rendered.getByText('data: null')).toBeInTheDocument()
318 await vi.advanceTimersByTimeAsync(10)
319 rendered.fixture.detectChanges()
320 expect(rendered.getByText('data: hydrated')).toBeInTheDocument()
321β
322 expect(states).toHaveLength(2)
323β
324 expect(fetched).toBe(false)
325β
326 expect(states[0]).toMatchObject({
327 status: 'pending',
328 fetchStatus: 'idle',
329 data: undefined,
330 })
331β
332 expect(states[1]).toMatchObject({
333 status: 'success',
334 fetchStatus: 'idle',
335 data: 'hydrated',
336 })
337 })
338β
339 it('should call onSuccess after successful restoring', async () => {
340 const key = createKey()
341 const queryClient = new QueryClient()
342 void queryClient
343 .query({
344 queryKey: key,
345 queryFn: () => sleep(10).then(() => 'hydrated'),
346 })
347 .catch(noop)
348 await vi.advanceTimersByTimeAsync(10)
349β
350 const persister = createMockPersister()
351 persistQueryClientSave({ queryClient, persister })
352 await vi.advanceTimersByTimeAsync(0)
353β
354 queryClient.clear()
355β
356 @Component({
357 template: `
358 <div>
359 <h1>{{ state.data() }}</h1>
360 <h2>fetchStatus: {{ state.fetchStatus() }}</h2>
361 </div>
362 `,
363 })
364 class Page {
365 state = injectQuery(() => ({
366 queryKey: key,
367 queryFn: () => sleep(10).then(() => 'fetched'),
368 }))
369 }
370β
371 const onSuccess = vi.fn<() => void>()
372β
373 const rendered = await render(Page, {
374 providers: [
375 provideZonelessChangeDetection(),
376 provideTanStackQuery(
377 queryClient,
378 withPersistQueryClient({
379 persistOptions: { persister },
380 onSuccess,
381 }),
382 ),
383 ],
384 })
385β
386 expect(onSuccess).toHaveBeenCalledTimes(0)
387 await vi.advanceTimersByTimeAsync(10)
388 rendered.fixture.detectChanges()
389 expect(rendered.getByText('hydrated')).toBeInTheDocument()
390 expect(onSuccess).toHaveBeenCalledTimes(1)
391 await vi.advanceTimersByTimeAsync(11)
392 rendered.fixture.detectChanges()
393 expect(rendered.getByText('fetched')).toBeInTheDocument()
394 })
395β
396 it('should remove cache after non-successful restoring', async () => {
397 const key = createKey()
398 const consoleErrorMock = vi
399 .spyOn(console, 'error')
400 .mockReturnValue(undefined)
401 const queryClient = new QueryClient()
402 const removeClient = vi.fn<() => Promisable<void>>()
403 const [error, persister] = createMockErrorPersister(removeClient)
404 const onSuccess = vi.fn<() => void>()
405 const onError = vi.fn<() => void>()
406β
407 @Component({
408 template: `
409 <div>
410 <h1>{{ state.data() }}</h1>
411 <h2>fetchStatus: {{ state.fetchStatus() }}</h2>
412 </div>
413 `,
414 })
415 class Page {
416 state = injectQuery(() => ({
417 queryKey: key,
418 queryFn: () => sleep(10).then(() => 'fetched'),
419 }))
420 }
421β
422 const rendered = await render(Page, {
423 providers: [
424 provideZonelessChangeDetection(),
425 provideTanStackQuery(
426 queryClient,
427 withPersistQueryClient({
428 persistOptions: { persister },
429 onSuccess,
430 onError,
431 }),
432 ),
433 ],
434 })
435β
436 await vi.advanceTimersByTimeAsync(10)
437 rendered.fixture.detectChanges()
438 expect(removeClient).toHaveBeenCalledTimes(1)
439 expect(onSuccess).toHaveBeenCalledTimes(0)
440 expect(onError).toHaveBeenCalledTimes(1)
441 await vi.advanceTimersByTimeAsync(11)
442 rendered.fixture.detectChanges()
443 expect(rendered.getByText('fetched')).toBeInTheDocument()
444β
445 expect(consoleErrorMock).toHaveBeenCalledTimes(1)
446 expect(consoleErrorMock).toHaveBeenNthCalledWith(1, error)
447 })
448})