Open History to see the last commit
1import {
2 sleep,
3 queryKey,
4 mockVisibilityState,
5 mockConsoleError,
6} from '../../react/tests/utils'
7import {
8 QueryCache,
9 QueryClient,
10 QueryObserver,
11 isCancelledError,
12 isError,
13 onlineManager,
14 QueryFunctionContext,
15} from '../..'
16β
17describe('query', () => {
18 let queryClient: QueryClient
19 let queryCache: QueryCache
20β
21 beforeEach(() => {
22 queryClient = new QueryClient()
23 queryCache = queryClient.getQueryCache()
24 queryClient.mount()
25 })
26β
27 afterEach(() => {
28 queryClient.clear()
29 })
30β
31 test('should use the longest cache time it has seen', async () => {
32 const key = queryKey()
33 await queryClient.prefetchQuery(key, () => 'data', {
34 cacheTime: 100,
35 })
36 await queryClient.prefetchQuery(key, () => 'data', {
37 cacheTime: 200,
38 })
39 await queryClient.prefetchQuery(key, () => 'data', {
40 cacheTime: 10,
41 })
42 const query = queryCache.find(key)!
43 expect(query.cacheTime).toBe(200)
44 })
45β
46 it('should continue retry after focus regain and resolve all promises', async () => {
47 const key = queryKey()
48β
49 const originalVisibilityState = document.visibilityState
50β
51 // make page unfocused
52 mockVisibilityState('hidden')
53β
54 let count = 0
55 let result
56β
57 const promise = queryClient.fetchQuery(
58 key,
59 async () => {
60 count++
61β
62 if (count === 3) {
63 return `data${count}`
64 }
65β
66 throw new Error(`error${count}`)
67 },
68 {
69 retry: 3,
70 retryDelay: 1,
71 }
72 )
73β
74 promise.then(data => {
75 result = data
76 })
77β
78 // Check if we do not have a result
79 expect(result).toBeUndefined()
80β
81 // Check if the query is really paused
82 await sleep(50)
83 expect(result).toBeUndefined()
84β
85 // Reset visibilityState to original value
86 mockVisibilityState(originalVisibilityState)
87 window.dispatchEvent(new FocusEvent('focus'))
88β
89 // There should not be a result yet
90 expect(result).toBeUndefined()
91β
92 // By now we should have a value
93 await sleep(50)
94 expect(result).toBe('data3')
95 })
96β
97 it('should continue retry after reconnect and resolve all promises', async () => {
98 const key = queryKey()
99β
100 onlineManager.setOnline(false)
101β
102 let count = 0
103 let result
104β
105 const promise = queryClient.fetchQuery(
106 key,
107 async () => {
108 count++
109β
110 if (count === 3) {
111 return `data${count}`
112 }
113β
114 throw new Error(`error${count}`)
115 },
116 {
117 retry: 3,
118 retryDelay: 1,
119 }
120 )
121β
122 promise.then(data => {
123 result = data
124 })
125β
126 // Check if we do not have a result
127 expect(result).toBeUndefined()
128β
129 // Check if the query is really paused
130 await sleep(50)
131 expect(result).toBeUndefined()
132β
133 // Reset navigator to original value
134 onlineManager.setOnline(true)
135β
136 // There should not be a result yet
137 expect(result).toBeUndefined()
138β
139 // By now we should have a value
140 await sleep(50)
141 expect(result).toBe('data3')
142 })
143β
144 it('should throw a CancelledError when a paused query is cancelled', async () => {
145 const key = queryKey()
146β
147 const originalVisibilityState = document.visibilityState
148β
149 // make page unfocused
150 mockVisibilityState('hidden')
151β
152 let count = 0
153 let result
154β
155 const promise = queryClient.fetchQuery(
156 key,
157 async () => {
158 count++
159 throw new Error(`error${count}`)
160 },
161 {
162 retry: 3,
163 retryDelay: 1,
164 }
165 )
166β
167 promise.catch(data => {
168 result = data
169 })
170β
171 const query = queryCache.find(key)!
172β
173 // Check if the query is really paused
174 await sleep(50)
175 expect(result).toBeUndefined()
176β
177 // Cancel query
178 query.cancel()
179β
180 // Check if the error is set to the cancelled error
181 await sleep(0)
182 expect(isCancelledError(result)).toBe(true)
183β
184 // Reset visibilityState to original value
185 mockVisibilityState(originalVisibilityState)
186 window.dispatchEvent(new FocusEvent('focus'))
187 })
188β
189 test('should provide context to queryFn', async () => {
190 const key = queryKey()
191β
192 const queryFn = jest
193 .fn<Promise<'data'>, [QueryFunctionContext<string>]>()
194 .mockResolvedValue('data')
195β
196 queryClient.prefetchQuery(key, queryFn)
197β
198 await sleep(10)
199β
200 expect(queryFn).toHaveBeenCalledTimes(1)
201 const args = queryFn.mock.calls[0]![0]
202 expect(args).toBeDefined()
203 expect(args.pageParam).toBeUndefined()
204 expect(args.queryKey).toEqual([key])
205 if (typeof AbortSignal === 'function') {
206 expect(args.signal).toBeInstanceOf(AbortSignal)
207 } else {
208 expect(args.signal).toBeUndefined()
209 }
210 })
211β
212 test('should continue if cancellation is not supported and signal is not consumed', async () => {
213 const key = queryKey()
214β
215 queryClient.prefetchQuery(key, async () => {
216 await sleep(100)
217 return 'data'
218 })
219β
220 await sleep(10)
221β
222 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
223 const observer = new QueryObserver(queryClient, {
224 queryKey: key,
225 enabled: false,
226 })
227 const unsubscribe = observer.subscribe()
228 unsubscribe()
229β
230 await sleep(100)
231β
232 const query = queryCache.find(key)!
233β
234 expect(query.state).toMatchObject({
235 data: 'data',
236 status: 'success',
237 dataUpdateCount: 1,
238 })
239 })
240β
241 test('should not continue when last observer unsubscribed if the signal was consumed', async () => {
242 const key = queryKey()
243β
244 queryClient.prefetchQuery(key, async ({ signal }) => {
245 await sleep(100)
246 return signal?.aborted ? 'aborted' : 'data'
247 })
248β
249 await sleep(10)
250β
251 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
252 const observer = new QueryObserver(queryClient, {
253 queryKey: key,
254 enabled: false,
255 })
256 const unsubscribe = observer.subscribe()
257 unsubscribe()
258β
259 await sleep(100)
260β
261 const query = queryCache.find(key)!
262β
263 if (typeof AbortSignal === 'function') {
264 expect(query.state).toMatchObject({
265 data: undefined,
266 status: 'idle',
267 })
268 } else {
269 expect(query.state).toMatchObject({
270 data: 'data',
271 status: 'success',
272 dataUpdateCount: 1,
273 })
274 }
275 })
276β
277 test('should provide an AbortSignal to the queryFn that provides info about the cancellation state', async () => {
278 const key = queryKey()
279β
280 const queryFn = jest.fn<Promise<void>, [QueryFunctionContext<string>]>()
281 const onAbort = jest.fn()
282 const abortListener = jest.fn()
283 let error
284β
285 queryFn.mockImplementation(async ({ signal }) => {
286 if (signal) {
287 signal.onabort = onAbort
288 signal.addEventListener('abort', abortListener)
289 }
290 await sleep(10)
291 if (signal) {
292 signal.onabort = null
293 signal.removeEventListener('abort', abortListener)
294 }
295 throw new Error()
296 })
297β
298 const promise = queryClient.fetchQuery(key, queryFn, {
299 retry: 3,
300 retryDelay: 10,
301 })
302β
303 promise.catch(e => {
304 error = e
305 })
306β
307 const query = queryCache.find(key)!
308β
309 expect(queryFn).toHaveBeenCalledTimes(1)
310β
311 let signal = queryFn.mock.calls[0]![0].signal
312β
313 if (typeof AbortSignal === 'function') {
314 signal = queryFn.mock.calls[0]![0].signal
315 expect(signal?.aborted).toBe(false)
316 }
317 expect(onAbort).not.toHaveBeenCalled()
318 expect(abortListener).not.toHaveBeenCalled()
319β
320 query.cancel()
321β
322 await sleep(100)
323β
324 if (typeof AbortSignal === 'function') {
325 expect(signal?.aborted).toBe(true)
326 expect(onAbort).toHaveBeenCalledTimes(1)
327 expect(abortListener).toHaveBeenCalledTimes(1)
328 }
329 expect(isCancelledError(error)).toBe(true)
330 })
331β
332 test('should call cancel() fn if it was provided and not continue when last observer unsubscribed', async () => {
333 const key = queryKey()
334β
335 const cancel = jest.fn()
336β
337 queryClient.prefetchQuery(key, async () => {
338 const promise = new Promise((resolve, reject) => {
339 sleep(100).then(() => resolve('data'))
340 cancel.mockImplementation(() => {
341 reject(new Error('Cancelled'))
342 })
343 }) as any
344 promise.cancel = cancel
345 return promise
346 })
347β
348 await sleep(10)
349β
350 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
351 const observer = new QueryObserver(queryClient, {
352 queryKey: key,
353 enabled: false,
354 })
355 const unsubscribe = observer.subscribe()
356 unsubscribe()
357β
358 await sleep(100)
359β
360 const query = queryCache.find(key)!
361β
362 expect(cancel).toHaveBeenCalled()
363 expect(query.state).toMatchObject({
364 data: undefined,
365 status: 'idle',
366 })
367 })
368β
369 test('should not continue if explicitly cancelled', async () => {
370 const key = queryKey()
371β
372 const queryFn = jest.fn()
373β
374 queryFn.mockImplementation(async () => {
375 await sleep(10)
376 throw new Error()
377 })
378β
379 let error
380β
381 const promise = queryClient.fetchQuery(key, queryFn, {
382 retry: 3,
383 retryDelay: 10,
384 })
385β
386 promise.catch(e => {
387 error = e
388 })
389β
390 const query = queryCache.find(key)!
391 query.cancel()
392β
393 await sleep(100)
394β
395 expect(queryFn).toHaveBeenCalledTimes(1)
396 expect(isCancelledError(error)).toBe(true)
397 })
398β
399 test('should not error if reset while loading', async () => {
400 const key = queryKey()
401β
402 const queryFn = jest.fn()
403β
404 queryFn.mockImplementation(async () => {
405 await sleep(10)
406 throw new Error()
407 })
408β
409 queryClient.fetchQuery(key, queryFn, {
410 retry: 3,
411 retryDelay: 10,
412 })
413β
414 // Ensure the query is loading
415 const query = queryCache.find(key)!
416 expect(query.state.status).toBe('loading')
417β
418 // Reset the query while it is loading
419 query.reset()
420β
421 await sleep(100)
422β
423 // The query should
424 expect(queryFn).toHaveBeenCalledTimes(1) // have been called,
425 expect(query.state.error).toBe(null) // not have an error, and
426 expect(query.state.status).toBe('idle') // not be loading any longer
427 })
428β
429 test('should be able to refetch a cancelled query', async () => {
430 const key = queryKey()
431β
432 const queryFn = jest.fn()
433β
434 queryFn.mockImplementation(async () => {
435 await sleep(50)
436 return 'data'
437 })
438β
439 queryClient.prefetchQuery(key, queryFn)
440 const query = queryCache.find(key)!
441 await sleep(10)
442 query.cancel()
443 await sleep(100)
444β
445 expect(queryFn).toHaveBeenCalledTimes(1)
446 expect(isCancelledError(query.state.error)).toBe(true)
447 const result = await query.fetch()
448 expect(result).toBe('data')
449 expect(query.state.error).toBe(null)
450 expect(queryFn).toHaveBeenCalledTimes(2)
451 })
452β
453 test('cancelling a resolved query should not have any effect', async () => {
454 const key = queryKey()
455 await queryClient.prefetchQuery(key, async () => 'data')
456 const query = queryCache.find(key)!
457 query.cancel()
458 await sleep(10)
459 expect(query.state.data).toBe('data')
460 })
461β
462 test('cancelling a rejected query should not have any effect', async () => {
463 const consoleMock = mockConsoleError()
464β
465 const key = queryKey()
466β
467 await queryClient.prefetchQuery(key, async () => {
468 throw new Error('error')
469 })
470 const query = queryCache.find(key)!
471 query.cancel()
472 await sleep(10)
473β
474 expect(isError(query.state.error)).toBe(true)
475 expect(isCancelledError(query.state.error)).toBe(false)
476β
477 consoleMock.mockRestore()
478 })
479β
480 test('the previous query status should be kept when refetching', async () => {
481 const consoleMock = mockConsoleError()
482 const key = queryKey()
483β
484 await queryClient.prefetchQuery(key, () => 'data')
485 const query = queryCache.find(key)!
486 expect(query.state.status).toBe('success')
487β
488 await queryClient.prefetchQuery(key, () => Promise.reject('reject'), {
489 retry: false,
490 })
491 expect(query.state.status).toBe('error')
492β
493 queryClient.prefetchQuery(
494 key,
495 async () => {
496 await sleep(10)
497 return Promise.reject('reject')
498 },
499 { retry: false }
500 )
501 expect(query.state.status).toBe('error')
502β
503 await sleep(100)
504 expect(query.state.status).toBe('error')
505β
506 consoleMock.mockRestore()
507 })
508β
509 test('queries with cacheTime 0 should be removed immediately after unsubscribing', async () => {
510 const consoleMock = mockConsoleError()
511 const key = queryKey()
512 let count = 0
513 const observer = new QueryObserver(queryClient, {
514 queryKey: key,
515 queryFn: () => {
516 count++
517 return 'data'
518 },
519 cacheTime: 0,
520 staleTime: Infinity,
521 })
522 const unsubscribe1 = observer.subscribe()
523 unsubscribe1()
524 await sleep(10)
525 const unsubscribe2 = observer.subscribe()
526 unsubscribe2()
527 await sleep(10)
528 expect(count).toBe(2)
529 expect(queryCache.find(key)).toBeUndefined()
530 consoleMock.mockRestore()
531 })
532β
533 test('should be garbage collected when unsubscribed to', async () => {
534 const key = queryKey()
535 const observer = new QueryObserver(queryClient, {
536 queryKey: key,
537 queryFn: async () => 'data',
538 cacheTime: 0,
539 })
540 expect(queryCache.find(key)).toBeDefined()
541 const unsubscribe = observer.subscribe()
542 expect(queryCache.find(key)).toBeDefined()
543 unsubscribe()
544 expect(queryCache.find(key)).toBeUndefined()
545 })
546β
547 test('should not be garbage collected unless there are no subscribers', async () => {
548 const key = queryKey()
549 const observer = new QueryObserver(queryClient, {
550 queryKey: key,
551 queryFn: async () => 'data',
552 cacheTime: 0,
553 })
554 expect(queryCache.find(key)).toBeDefined()
555 const unsubscribe = observer.subscribe()
556 await sleep(100)
557 expect(queryCache.find(key)).toBeDefined()
558 unsubscribe()
559 await sleep(100)
560 expect(queryCache.find(key)).toBeUndefined()
561 queryClient.setQueryData(key, 'data')
562 await sleep(100)
563 expect(queryCache.find(key)).toBeDefined()
564 })
565β
566 test('should return proper count of observers', async () => {
567 const key = queryKey()
568 const options = { queryKey: key, queryFn: async () => 'data' }
569 const observer = new QueryObserver(queryClient, options)
570 const observer2 = new QueryObserver(queryClient, options)
571 const observer3 = new QueryObserver(queryClient, options)
572 const query = queryCache.find(key)
573β
574 expect(query?.getObserversCount()).toEqual(0)
575β
576 const unsubscribe1 = observer.subscribe()
577 const unsubscribe2 = observer2.subscribe()
578 const unsubscribe3 = observer3.subscribe()
579 expect(query?.getObserversCount()).toEqual(3)
580β
581 unsubscribe3()
582 expect(query?.getObserversCount()).toEqual(2)
583β
584 unsubscribe2()
585 expect(query?.getObserversCount()).toEqual(1)
586β
587 unsubscribe1()
588 expect(query?.getObserversCount()).toEqual(0)
589 })
590β
591 test('stores meta object in query', async () => {
592 const meta = {
593 it: 'works',
594 }
595β
596 const key = queryKey()
597β
598 await queryClient.prefetchQuery(key, () => 'data', {
599 meta,
600 })
601β
602 const query = queryCache.find(key)!
603β
604 expect(query.meta).toBe(meta)
605 expect(query.options.meta).toBe(meta)
606 })
607β
608 test('updates meta object on change', async () => {
609 const meta = {
610 it: 'works',
611 }
612β
613 const key = queryKey()
614 const queryFn = () => 'data'
615β
616 await queryClient.prefetchQuery(key, queryFn, {
617 meta,
618 })
619β
620 await queryClient.prefetchQuery(key, queryFn, {
621 meta: undefined,
622 })
623β
624 const query = queryCache.find(key)!
625β
626 expect(query.meta).toBeUndefined()
627 expect(query.options.meta).toBeUndefined()
628 })
629β
630 test('provides meta object inside query function', async () => {
631 const meta = {
632 it: 'works',
633 }
634β
635 const queryFn = jest.fn(() => 'data')
636β
637 const key = queryKey()
638β
639 await queryClient.prefetchQuery(key, queryFn, {
640 meta,
641 })
642β
643 expect(queryFn).toBeCalledWith(
644 expect.objectContaining({
645 meta,
646 })
647 )
648 })
649})