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

useQuery.test.ts

781 lines20.1 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 computed,
4 getCurrentInstance,
5 onScopeDispose,
6 reactive,
7 ref,
8} from 'vue-demi'
9import { QueryObserver, experimental_streamedQuery } from '@tanstack/query-core'
10import { queryKey, sleep } from '@tanstack/query-test-utils'
11import { keepPreviousData } from '..'
12import { useQuery } from '../useQuery'
13import { useBaseQuery } from '../useBaseQuery'
14import { useQueryClient } from '../useQueryClient'
15import type { Mock, MockedFunction } from 'vitest'
16​
17vi.mock('../useQueryClient')
18vi.mock('../useBaseQuery')
19​
20describe('useQuery', () => {
21 beforeEach(() => {
22 vi.useFakeTimers()
23 })
24​
25 afterEach(() => {
26 vi.useRealTimers()
27 })
28​
29 it('should properly execute query', () => {
30 const key = queryKey()
31 const queryFn = () => sleep(0).then(() => 'Some data')
32​
33 useQuery({
34 queryKey: key,
35 queryFn,
36 staleTime: 1000,
37 })
38​
39 expect(useBaseQuery).toHaveBeenCalledWith(
40 QueryObserver,
41 {
42 queryKey: key,
43 queryFn,
44 staleTime: 1000,
45 },
46 undefined,
47 )
48 })
49​
50 it('should work with options getter', async () => {
51 const key = queryKey()
52 const query = useQuery(() => ({
53 queryKey: key,
54 queryFn: () => sleep(0).then(() => 'result01'),
55 }))
56​
57 await vi.advanceTimersByTimeAsync(0)
58​
59 expect(query).toMatchObject({
60 status: { value: 'success' },
61 data: { value: 'result01' },
62 isPending: { value: false },
63 isFetching: { value: false },
64 isFetched: { value: true },
65 isSuccess: { value: true },
66 })
67 })
68​
69 it('should work with options getter and be reactive', async () => {
70 const key = queryKey()
71 const keyRef = ref('key011')
72 const resultRef = ref('result02')
73 const query = useQuery(() => ({
74 queryKey: [...key, keyRef.value],
75 queryFn: () => sleep(0).then(() => resultRef.value),
76 }))
77​
78 await vi.advanceTimersByTimeAsync(0)
79​
80 expect(query).toMatchObject({
81 status: { value: 'success' },
82 data: { value: 'result02' },
83 isPending: { value: false },
84 isFetching: { value: false },
85 isFetched: { value: true },
86 isSuccess: { value: true },
87 })
88​
89 resultRef.value = 'result021'
90 keyRef.value = 'key012'
91 await vi.advanceTimersByTimeAsync(0)
92​
93 expect(query).toMatchObject({
94 status: { value: 'success' },
95 data: { value: 'result021' },
96 isPending: { value: false },
97 isFetching: { value: false },
98 isFetched: { value: true },
99 isSuccess: { value: true },
100 })
101 })
102​
103 it('should return pending status initially', () => {
104 const key = queryKey()
105 const query = useQuery({
106 queryKey: key,
107 queryFn: () => sleep(0).then(() => 'Some data'),
108 })
109​
110 expect(query).toMatchObject({
111 status: { value: 'pending' },
112 isPending: { value: true },
113 isFetching: { value: true },
114 isStale: { value: true },
115 })
116 })
117​
118 it('should resolve to success and update reactive state: useQuery(key, dataFn)', async () => {
119 const key = queryKey()
120 const query = useQuery({
121 queryKey: key,
122 queryFn: () => sleep(0).then(() => 'result2'),
123 })
124​
125 await vi.advanceTimersByTimeAsync(0)
126​
127 expect(query).toMatchObject({
128 status: { value: 'success' },
129 data: { value: 'result2' },
130 isPending: { value: false },
131 isFetching: { value: false },
132 isFetched: { value: true },
133 isSuccess: { value: true },
134 })
135 })
136​
137 it('should resolve to success and update reactive state: useQuery(optionsObj)', async () => {
138 const key = queryKey()
139 const query = useQuery({
140 queryKey: key,
141 queryFn: () => sleep(0).then(() => 'result31'),
142 enabled: true,
143 })
144​
145 await vi.advanceTimersByTimeAsync(0)
146​
147 expect(query).toMatchObject({
148 status: { value: 'success' },
149 data: { value: 'result31' },
150 isPending: { value: false },
151 isFetching: { value: false },
152 isFetched: { value: true },
153 isSuccess: { value: true },
154 })
155 })
156​
157 it('should resolve to success and update reactive state: useQuery(key, optionsObj)', async () => {
158 const key = queryKey()
159 const query = useQuery({
160 queryKey: key,
161 queryFn: () => sleep(0).then(() => 'result32'),
162 enabled: true,
163 })
164​
165 await vi.advanceTimersByTimeAsync(0)
166​
167 expect(query).toMatchObject({
168 status: { value: 'success' },
169 data: { value: 'result32' },
170 isPending: { value: false },
171 isFetching: { value: false },
172 isFetched: { value: true },
173 isSuccess: { value: true },
174 })
175 })
176​
177 it('should reject and update reactive state', async () => {
178 const key = queryKey()
179 const query = useQuery({
180 queryKey: key,
181 queryFn: () =>
182 sleep(0).then(() => Promise.reject(new Error('Some error'))),
183 })
184​
185 await vi.advanceTimersByTimeAsync(0)
186​
187 expect(query).toMatchObject({
188 status: { value: 'error' },
189 data: { value: undefined },
190 error: { value: { message: 'Some error' } },
191 isPending: { value: false },
192 isFetching: { value: false },
193 isFetched: { value: true },
194 isError: { value: true },
195 failureCount: { value: 1 },
196 failureReason: { value: { message: 'Some error' } },
197 })
198 })
199​
200 it('should update query on reactive (Ref) key change', async () => {
201 const key = queryKey()
202 const secondKeyRef = ref('key7')
203 const query = useQuery({
204 queryKey: [...key, secondKeyRef],
205 queryFn: () => sleep(10).then(() => 'Some data'),
206 })
207​
208 await vi.advanceTimersByTimeAsync(10)
209​
210 expect(query).toMatchObject({
211 status: { value: 'success' },
212 })
213​
214 secondKeyRef.value = 'key8'
215 await vi.advanceTimersByTimeAsync(0)
216​
217 expect(query).toMatchObject({
218 status: { value: 'pending' },
219 data: { value: undefined },
220 })
221​
222 await vi.advanceTimersByTimeAsync(10)
223​
224 expect(query).toMatchObject({
225 status: { value: 'success' },
226 })
227 })
228​
229 it("should update query when an option is passed as Ref and it's changed", async () => {
230 const key = queryKey()
231 const enabled = ref(false)
232 const query = useQuery({
233 queryKey: key,
234 queryFn: () => sleep(10).then(() => 'Some data'),
235 enabled,
236 })
237​
238 await vi.advanceTimersByTimeAsync(0)
239​
240 expect(query).toMatchObject({
241 fetchStatus: { value: 'idle' },
242 data: { value: undefined },
243 })
244​
245 enabled.value = true
246​
247 await vi.advanceTimersByTimeAsync(0)
248​
249 expect(query).toMatchObject({
250 fetchStatus: { value: 'fetching' },
251 data: { value: undefined },
252 })
253​
254 await vi.advanceTimersByTimeAsync(10)
255​
256 expect(query).toMatchObject({
257 status: { value: 'success' },
258 })
259 })
260​
261 it('should properly execute dependent queries', async () => {
262 const key1 = queryKey()
263 const key2 = queryKey()
264 const { data } = useQuery({
265 queryKey: key1,
266 queryFn: () => sleep(0).then(() => 'Some data'),
267 })
268​
269 const enabled = computed(() => !!data.value)
270​
271 const dependentQueryFn = vi
272 .fn()
273 .mockImplementation(() => sleep(10).then(() => 'Some data'))
274 const { fetchStatus, status } = useQuery(
275 reactive({
276 queryKey: key2,
277 queryFn: dependentQueryFn,
278 enabled,
279 }),
280 )
281​
282 expect(data.value).toStrictEqual(undefined)
283 expect(fetchStatus.value).toStrictEqual('idle')
284 expect(dependentQueryFn).not.toHaveBeenCalled()
285​
286 await vi.advanceTimersByTimeAsync(0)
287​
288 expect(data.value).toStrictEqual('Some data')
289 expect(fetchStatus.value).toStrictEqual('fetching')
290​
291 await vi.advanceTimersByTimeAsync(10)
292​
293 expect(fetchStatus.value).toStrictEqual('idle')
294 expect(status.value).toStrictEqual('success')
295 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
296 expect(dependentQueryFn).toHaveBeenCalledWith(
297 expect.objectContaining({ queryKey: key2 }),
298 )
299 })
300​
301 it('should stop listening to changes on onScopeDispose', async () => {
302 const key = queryKey()
303 const onScopeDisposeMock = onScopeDispose as MockedFunction<
304 typeof onScopeDispose
305 >
306 onScopeDisposeMock.mockImplementationOnce((fn) => fn())
307​
308 const { status } = useQuery({
309 queryKey: key,
310 queryFn: () => sleep(0).then(() => 'Some data'),
311 })
312​
313 expect(status.value).toStrictEqual('pending')
314​
315 await vi.advanceTimersByTimeAsync(0)
316​
317 expect(status.value).toStrictEqual('pending')
318​
319 await vi.advanceTimersByTimeAsync(0)
320​
321 expect(status.value).toStrictEqual('pending')
322 })
323​
324 it('should use the current value for the queryKey when refetch is called', async () => {
325 const key = queryKey()
326 const fetchFn = vi.fn(() => 'foo')
327 const keyRef = ref('key11')
328 const query = useQuery({
329 queryKey: [...key, keyRef],
330 queryFn: fetchFn,
331 enabled: false,
332 })
333​
334 expect(fetchFn).not.toHaveBeenCalled()
335 await query.refetch()
336 expect(fetchFn).toHaveBeenCalledTimes(1)
337 expect(fetchFn).toHaveBeenNthCalledWith(
338 1,
339 expect.objectContaining({
340 queryKey: [...key, 'key11'],
341 }),
342 )
343​
344 keyRef.value = 'key12'
345 await query.refetch()
346 expect(fetchFn).toHaveBeenCalledTimes(2)
347 expect(fetchFn).toHaveBeenNthCalledWith(
348 2,
349 expect.objectContaining({
350 queryKey: [...key, 'key12'],
351 }),
352 )
353 })
354​
355 it('should be `enabled` to accept getter function', async () => {
356 const key = queryKey()
357 const fetchFn = vi.fn(() => 'foo')
358 const checked = ref(false)
359​
360 useQuery({
361 queryKey: key,
362 queryFn: fetchFn,
363 enabled: () => checked.value,
364 })
365​
366 expect(fetchFn).not.toHaveBeenCalled()
367​
368 checked.value = true
369​
370 await vi.advanceTimersByTimeAsync(0)
371​
372 expect(fetchFn).toHaveBeenCalled()
373 })
374​
375 it('should allow getters for query keys', async () => {
376 const key = queryKey()
377 const fetchFn = vi.fn(() => 'foo')
378 const key1 = ref('key1')
379 const key2 = ref('key2')
380​
381 useQuery({
382 queryKey: [...key, () => key1.value, () => key2.value],
383 queryFn: fetchFn,
384 })
385​
386 expect(fetchFn).toHaveBeenCalledTimes(1)
387​
388 key1.value = 'key3'
389​
390 await vi.advanceTimersByTimeAsync(0)
391​
392 expect(fetchFn).toHaveBeenCalledTimes(2)
393​
394 key2.value = 'key4'
395​
396 await vi.advanceTimersByTimeAsync(0)
397​
398 expect(fetchFn).toHaveBeenCalledTimes(3)
399 })
400​
401 it('should allow arbitrarily nested getters for query keys', async () => {
402 const key = queryKey()
403 const fetchFn = vi.fn(() => 'foo')
404 const key1 = ref('key1')
405 const key2 = ref('key2')
406 const key3 = ref('key3')
407 const key4 = ref('key4')
408 const key5 = ref('key5')
409​
410 useQuery({
411 queryKey: [
412 ...key,
413 key1,
414 () => key2.value,
415 { key: () => key3.value },
416 [{ foo: { bar: () => key4.value } }],
417 () => ({
418 foo: {
419 bar: {
420 baz: () => key5.value,
421 },
422 },
423 }),
424 ],
425 queryFn: fetchFn,
426 })
427​
428 expect(fetchFn).toHaveBeenCalledTimes(1)
429​
430 key1.value = 'key1-updated'
431​
432 await vi.advanceTimersByTimeAsync(0)
433​
434 expect(fetchFn).toHaveBeenCalledTimes(2)
435​
436 key2.value = 'key2-updated'
437​
438 await vi.advanceTimersByTimeAsync(0)
439​
440 expect(fetchFn).toHaveBeenCalledTimes(3)
441​
442 key3.value = 'key3-updated'
443​
444 await vi.advanceTimersByTimeAsync(0)
445​
446 expect(fetchFn).toHaveBeenCalledTimes(4)
447​
448 key4.value = 'key4-updated'
449​
450 await vi.advanceTimersByTimeAsync(0)
451​
452 expect(fetchFn).toHaveBeenCalledTimes(5)
453​
454 key5.value = 'key5-updated'
455​
456 await vi.advanceTimersByTimeAsync(0)
457​
458 expect(fetchFn).toHaveBeenCalledTimes(6)
459 })
460​
461 it('should derive data via select without changing what is cached', async () => {
462 const key = queryKey()
463 const query = useQuery({
464 queryKey: key,
465 queryFn: () => sleep(10).then(() => ['a', 'b', 'c']),
466 select: (posts) => posts.length,
467 })
468​
469 await vi.advanceTimersByTimeAsync(10)
470​
471 expect(query).toMatchObject({
472 status: { value: 'success' },
473 data: { value: 3 },
474 })
475​
476 const queryClient = useQueryClient()
477 expect(queryClient.getQueryData(key)).toEqual(['a', 'b', 'c'])
478 })
479​
480 it('should stay disabled until the dependent value is set', async () => {
481 const key = queryKey()
482 const postId = ref<number>()
483 const fetchFn = vi.fn(() => sleep(10).then(() => 'Some data'))
484​
485 const query = useQuery({
486 queryKey: [...key, postId],
487 queryFn: fetchFn,
488 enabled: () => postId.value != null,
489 })
490​
491 await vi.advanceTimersByTimeAsync(10)
492​
493 expect(fetchFn).not.toHaveBeenCalled()
494 expect(query).toMatchObject({ status: { value: 'pending' } })
495​
496 postId.value = 1
497​
498 await vi.advanceTimersByTimeAsync(10)
499​
500 expect(fetchFn).toHaveBeenCalledTimes(1)
501 expect(query).toMatchObject({
502 status: { value: 'success' },
503 data: { value: 'Some data' },
504 })
505 })
506​
507 it('should seed from initialData and skip the loading state', () => {
508 const key = queryKey()
509 const query = useQuery({
510 queryKey: key,
511 queryFn: () => sleep(10).then(() => 'fetched data'),
512 initialData: 'seeded data',
513 })
514​
515 expect(query).toMatchObject({
516 status: { value: 'success' },
517 data: { value: 'seeded data' },
518 })
519 })
520​
521 it('should still fetch in the background and replace initialData with the fetched value', async () => {
522 const key = queryKey()
523 const fetchFn = vi.fn(() => sleep(10).then(() => 'fetched data'))
524​
525 const query = useQuery({
526 queryKey: key,
527 queryFn: fetchFn,
528 initialData: 'seeded data',
529 })
530​
531 await vi.advanceTimersByTimeAsync(10)
532​
533 expect(fetchFn).toHaveBeenCalledTimes(1)
534 expect(query).toMatchObject({
535 status: { value: 'success' },
536 data: { value: 'fetched data' },
537 })
538 })
539​
540 it('should keep the previous page visible while the next page loads with keepPreviousData', async () => {
541 const key = queryKey()
542 const page = ref(0)
543 const fetchFn = vi.fn((pageParam: number) =>
544 sleep(10).then(() => `page-${pageParam}`),
545 )
546​
547 const query = useQuery({
548 queryKey: [...key, page],
549 queryFn: () => fetchFn(page.value),
550 placeholderData: keepPreviousData,
551 })
552​
553 await vi.advanceTimersByTimeAsync(10)
554​
555 expect(query).toMatchObject({
556 data: { value: 'page-0' },
557 isPlaceholderData: { value: false },
558 })
559​
560 page.value = 1
561​
562 await vi.advanceTimersByTimeAsync(0)
563​
564 expect(query).toMatchObject({
565 data: { value: 'page-0' },
566 isPlaceholderData: { value: true },
567 })
568​
569 await vi.advanceTimersByTimeAsync(10)
570​
571 expect(query).toMatchObject({
572 data: { value: 'page-1' },
573 isPlaceholderData: { value: false },
574 })
575 })
576​
577 describe('throwOnError', () => {
578 it('should evaluate throwOnError when query is expected to throw', async () => {
579 const key = queryKey()
580 const boundaryFn = vi.fn()
581 useQuery({
582 queryKey: key,
583 queryFn: () =>
584 sleep(0).then(() => Promise.reject(new Error('Some error'))),
585 retry: false,
586 throwOnError: boundaryFn,
587 })
588​
589 await vi.advanceTimersByTimeAsync(0)
590​
591 expect(boundaryFn).toHaveBeenCalledTimes(1)
592 expect(boundaryFn).toHaveBeenCalledWith(
593 Error('Some error'),
594 expect.objectContaining({
595 state: expect.objectContaining({ status: 'error' }),
596 }),
597 )
598 })
599 })
600​
601 describe('outside scope warning', () => {
602 it('should warn when used outside of setup function in development mode', () => {
603 vi.stubEnv('NODE_ENV', 'development')
604 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
605​
606 try {
607 useQuery({
608 queryKey: queryKey(),
609 queryFn: () => sleep(0).then(() => 'data'),
610 })
611​
612 expect(warnSpy).toHaveBeenCalledWith(
613 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
614 )
615 } finally {
616 warnSpy.mockRestore()
617 vi.unstubAllEnvs()
618 }
619 })
620 })
621​
622 describe('suspense', () => {
623 it('should return a Promise', () => {
624 const key = queryKey()
625 const getCurrentInstanceSpy = getCurrentInstance as Mock
626 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
627​
628 const query = useQuery({
629 queryKey: key,
630 queryFn: () => sleep(0).then(() => 'Some data'),
631 })
632 const result = query.suspense()
633​
634 expect(result).toBeInstanceOf(Promise)
635 })
636​
637 it('should resolve after being enabled', async () => {
638 const key = queryKey()
639 const getCurrentInstanceSpy = getCurrentInstance as Mock
640 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
641​
642 let afterTimeout = false
643 const isEnabled = ref(false)
644 const query = useQuery({
645 queryKey: key,
646 queryFn: () => sleep(0).then(() => 'Some data'),
647 enabled: isEnabled,
648 })
649​
650 setTimeout(() => {
651 afterTimeout = true
652 isEnabled.value = true
653 }, 200)
654​
655 query.suspense()
656​
657 await vi.advanceTimersByTimeAsync(200)
658​
659 expect(afterTimeout).toBe(true)
660 })
661​
662 it('should resolve immediately when stale without refetching', () => {
663 const key = queryKey()
664 const getCurrentInstanceSpy = getCurrentInstance as Mock
665 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
666​
667 const fetcherSpy = vi.fn(() => sleep(0).then(() => 'Some data'))
668​
669 // let afterTimeout = false;
670 const query = useQuery({
671 queryKey: key,
672 queryFn: () => sleep(0).then(() => 'Some data'),
673 staleTime: 10000,
674 initialData: 'foo',
675 })
676​
677 return query.suspense().then(() => {
678 expect(fetcherSpy).toHaveBeenCalledTimes(0)
679 })
680 })
681​
682 it('should not throw from suspense by default', async () => {
683 const key = queryKey()
684 const getCurrentInstanceSpy = getCurrentInstance as Mock
685 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
686​
687 const query = useQuery({
688 queryKey: key,
689 queryFn: () =>
690 sleep(0).then(() => Promise.reject(new Error('Some error'))),
691 staleTime: 10000,
692 })
693​
694 await vi.advanceTimersByTimeAsync(0)
695​
696 expect(query).toMatchObject({
697 status: { value: 'error' },
698 isError: { value: true },
699 })
700 })
701​
702 it('should throw from suspense when throwOnError is true', async () => {
703 const key = queryKey()
704 const getCurrentInstanceSpy = getCurrentInstance as Mock
705 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
706​
707 const boundaryFn = vi.fn()
708 const query = useQuery({
709 queryKey: key,
710 queryFn: () =>
711 sleep(0).then(() => Promise.reject(new Error('Some error'))),
712 staleTime: 10000,
713 throwOnError: boundaryFn,
714 })
715​
716 query.suspense()
717​
718 await vi.advanceTimersByTimeAsync(10000)
719​
720 expect(boundaryFn).toHaveBeenCalledTimes(2)
721 expect(boundaryFn).toHaveBeenNthCalledWith(
722 1,
723 Error('Some error'),
724 expect.objectContaining({
725 state: expect.objectContaining({ status: 'error' }),
726 }),
727 )
728 expect(boundaryFn).toHaveBeenNthCalledWith(
729 2,
730 Error('Some error'),
731 expect.objectContaining({
732 state: expect.objectContaining({ status: 'error' }),
733 }),
734 )
735 })
736​
737 it('should release suspense when setQueryData is called while fetch is in-flight', async () => {
738 const key = queryKey()
739​
740 const query = useQuery({
741 queryKey: key,
742 queryFn: () => sleep(10000).then(() => 'fetched'),
743 })
744​
745 const suspensePromise = query.suspense()
746​
747 const queryClient = useQueryClient()
748 queryClient.setQueryData(key, 'manual data')
749​
750 await vi.advanceTimersByTimeAsync(0)
751​
752 const result = await suspensePromise
753 expect(result.data).toBe('manual data')
754 })
755​
756 it('should release suspense when streamedQuery receives first chunk', async () => {
757 const key = queryKey()
758​
759 async function* numberGenerator() {
760 await sleep(10)
761 yield 'chunk1'
762 await sleep(10)
763 yield 'chunk2'
764 }
765​
766 const query = useQuery({
767 queryKey: key,
768 queryFn: experimental_streamedQuery({
769 streamFn: () => numberGenerator(),
770 }),
771 })
772​
773 const suspensePromise = query.suspense()
774​
775 await vi.advanceTimersByTimeAsync(10)
776​
777 const result = await suspensePromise
778 expect(result.data).toStrictEqual(['chunk1'])
779 })
780 })
781})