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