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

with-persist-query-client.test.ts

406 lines9.5 KB

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