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