Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 computed,
4 isReactive,
5 isReadonly,
6 isRef,
7 isVue3,
8 onScopeDispose,
9 reactive,
10 ref,
11} from 'vue-demi'
12import {
13 QueryObserver,
14 experimental_streamedQuery,
15 noop,
16 skipToken,
17} from '@tanstack/query-core'
18import { createKey, sleep } from '@tanstack/query-test-utils'
19import { keepPreviousData } from '..'
20import { useQuery } from '../useQuery'
21import { useBaseQuery } from '../useBaseQuery'
22import { useQueryClient } from '../useQueryClient'
23import type { Query, QueryObserverResult } from '@tanstack/query-core'
24β
25vi.mock(import('../useQueryClient'))
26vi.mock(import('../useBaseQuery'))
27β
28describe('useQuery', () => {
29 beforeEach(() => {
30 vi.useFakeTimers()
31 })
32β
33 afterEach(() => {
34 vi.useRealTimers()
35 })
36β
37 it('should properly execute query', () => {
38 const key = createKey()
39 const queryFn = () => sleep(0).then(() => 'Some data')
40β
41 useQuery({
42 queryKey: key,
43 queryFn,
44 staleTime: 1000,
45 })
46β
47 expect(useBaseQuery).toHaveBeenCalledWith(
48 QueryObserver,
49 {
50 queryKey: key,
51 queryFn,
52 staleTime: 1000,
53 },
54 undefined,
55 )
56 })
57β
58 it('should work with options getter', async () => {
59 const key = createKey()
60 const query = useQuery(() => ({
61 queryKey: key,
62 queryFn: () => sleep(0).then(() => 'result01'),
63 }))
64β
65 await vi.advanceTimersByTimeAsync(0)
66 expect(query).toMatchObject({
67 status: { value: 'success' },
68 data: { value: 'result01' },
69 isPending: { value: false },
70 isFetching: { value: false },
71 isFetched: { value: true },
72 isSuccess: { value: true },
73 })
74 })
75β
76 it('should work with options getter and be reactive', async () => {
77 const key = createKey()
78 const keyRef = ref('key011')
79 const resultRef = ref('result02')
80 const query = useQuery(() => ({
81 queryKey: [...key, keyRef.value],
82 queryFn: () => sleep(0).then(() => resultRef.value),
83 }))
84β
85 await vi.advanceTimersByTimeAsync(0)
86 expect(query).toMatchObject({
87 status: { value: 'success' },
88 data: { value: 'result02' },
89 isPending: { value: false },
90 isFetching: { value: false },
91 isFetched: { value: true },
92 isSuccess: { value: true },
93 })
94β
95 resultRef.value = 'result021'
96 keyRef.value = 'key012'
97 await vi.advanceTimersByTimeAsync(0)
98 expect(query).toMatchObject({
99 status: { value: 'success' },
100 data: { value: 'result021' },
101 isPending: { value: false },
102 isFetching: { value: false },
103 isFetched: { value: true },
104 isSuccess: { value: true },
105 })
106 })
107β
108 it('should expose data, status, and isPending on state without ref unwrapping', async () => {
109 const key = createKey()
110 const query = useQuery({
111 queryKey: key,
112 queryFn: () => sleep(10).then(() => 'Some data'),
113 })
114β
115 expect(isRef(query.state)).toBe(false)
116 expect(isReadonly(query.state)).toBe(true)
117 expect(query.state.status).toBe('pending')
118 expect(query.state.isPending).toBe(true)
119 expect(query.state.data).toBeUndefined()
120 expect(query.state.error).toBeNull()
121β
122 const status = computed(() => query.state.status)
123 const data = computed(() => query.state.data)
124β
125 await vi.advanceTimersByTimeAsync(10)
126β
127 expect(query.state.status).toBe('success')
128 expect(query.state.isPending).toBe(false)
129 expect(query.state.isSuccess).toBe(true)
130 expect(query.state.data).toBe('Some data')
131 expect(query.state.error).toBeNull()
132 expect(query.data.value).toBe(query.state.data)
133 expect(query.status.value).toBe(query.state.status)
134 expect(status.value).toBe('success')
135 expect(data.value).toBe('Some data')
136 expect(query.state.refetch).toBeTypeOf('function')
137β
138 const refetchResult = query.refetch()
139 await vi.advanceTimersByTimeAsync(10)
140 await refetchResult
141 expect(query.state.data).toBe('Some data')
142 expect(query.state.status).toBe('success')
143 })
144β
145 it('should keep function-valued data on state when select returns a function', async () => {
146 const key = createKey()
147 const { state } = useQuery({
148 queryKey: key,
149 queryFn: () => sleep(10).then(() => 'fetched'),
150 initialData: 'initial',
151 select: (value: string) => () => value,
152 })
153β
154 expect(state.status).toBe('success')
155 expect(state.data()).toBe('initial')
156β
157 await vi.advanceTimersByTimeAsync(10)
158β
159 expect(state.status).toBe('success')
160 expect(state.data()).toBe('fetched')
161 })
162β
163 it('should return pending status initially', () => {
164 const key = createKey()
165 const query = useQuery({
166 queryKey: key,
167 queryFn: () => sleep(0).then(() => 'Some data'),
168 })
169β
170 expect(query).toMatchObject({
171 status: { value: 'pending' },
172 isPending: { value: true },
173 isFetching: { value: true },
174 isStale: { value: true },
175 })
176 })
177β
178 it('should resolve to success and update reactive state: useQuery(key, dataFn)', async () => {
179 const key = createKey()
180 const query = useQuery({
181 queryKey: key,
182 queryFn: () => sleep(0).then(() => 'result2'),
183 })
184β
185 await vi.advanceTimersByTimeAsync(0)
186 expect(query).toMatchObject({
187 status: { value: 'success' },
188 data: { value: 'result2' },
189 isPending: { value: false },
190 isFetching: { value: false },
191 isFetched: { value: true },
192 isSuccess: { value: true },
193 })
194 })
195β
196 it('should resolve to success and update reactive state: useQuery(optionsObj)', async () => {
197 const key = createKey()
198 const query = useQuery({
199 queryKey: key,
200 queryFn: () => sleep(0).then(() => 'result31'),
201 enabled: true,
202 })
203β
204 await vi.advanceTimersByTimeAsync(0)
205 expect(query).toMatchObject({
206 status: { value: 'success' },
207 data: { value: 'result31' },
208 isPending: { value: false },
209 isFetching: { value: false },
210 isFetched: { value: true },
211 isSuccess: { value: true },
212 })
213 })
214β
215 it('should resolve to success and update reactive state: useQuery(key, optionsObj)', async () => {
216 const key = createKey()
217 const query = useQuery({
218 queryKey: key,
219 queryFn: () => sleep(0).then(() => 'result32'),
220 enabled: true,
221 })
222β
223 await vi.advanceTimersByTimeAsync(0)
224 expect(query).toMatchObject({
225 status: { value: 'success' },
226 data: { value: 'result32' },
227 isPending: { value: false },
228 isFetching: { value: false },
229 isFetched: { value: true },
230 isSuccess: { value: true },
231 })
232 })
233β
234 it('should reject and update reactive state', async () => {
235 const key = createKey()
236 const query = useQuery({
237 queryKey: key,
238 queryFn: () =>
239 sleep(0).then(() => Promise.reject(new Error('Some error'))),
240 })
241β
242 await vi.advanceTimersByTimeAsync(0)
243 expect(query).toMatchObject({
244 status: { value: 'error' },
245 data: { value: undefined },
246 error: { value: { message: 'Some error' } },
247 isPending: { value: false },
248 isFetching: { value: false },
249 isFetched: { value: true },
250 isError: { value: true },
251 failureCount: { value: 1 },
252 failureReason: { value: { message: 'Some error' } },
253 })
254 })
255β
256 it('should update query on reactive (Ref) key change', async () => {
257 const key = createKey()
258 const secondKeyRef = ref('key7')
259 const query = useQuery({
260 queryKey: [...key, secondKeyRef],
261 queryFn: () => sleep(10).then(() => 'Some data'),
262 })
263β
264 await vi.advanceTimersByTimeAsync(10)
265 expect(query).toMatchObject({
266 status: { value: 'success' },
267 })
268β
269 secondKeyRef.value = 'key8'
270 await vi.advanceTimersByTimeAsync(0)
271 expect(query).toMatchObject({
272 status: { value: 'pending' },
273 data: { value: undefined },
274 })
275 await vi.advanceTimersByTimeAsync(10)
276 expect(query).toMatchObject({
277 status: { value: 'success' },
278 })
279 })
280β
281 it("should update query when an option is passed as Ref and it's changed", async () => {
282 const key = createKey()
283 const enabled = ref(false)
284 const query = useQuery({
285 queryKey: key,
286 queryFn: () => sleep(10).then(() => 'Some data'),
287 enabled,
288 })
289β
290 await vi.advanceTimersByTimeAsync(0)
291 expect(query).toMatchObject({
292 fetchStatus: { value: 'idle' },
293 data: { value: undefined },
294 })
295β
296 enabled.value = true
297 await vi.advanceTimersByTimeAsync(0)
298 expect(query).toMatchObject({
299 fetchStatus: { value: 'fetching' },
300 data: { value: undefined },
301 })
302 await vi.advanceTimersByTimeAsync(10)
303 expect(query).toMatchObject({
304 status: { value: 'success' },
305 })
306 })
307β
308 it('should properly execute dependent queries', async () => {
309 const key1 = createKey()
310 const key2 = createKey()
311 const { data } = useQuery({
312 queryKey: key1,
313 queryFn: () => sleep(0).then(() => 'Some data'),
314 })
315β
316 const enabled = computed(() => !!data.value)
317β
318 const dependentQueryFn = vi.fn<() => Promise<string>>(() =>
319 sleep(10).then(() => 'Some data'),
320 )
321 const { fetchStatus, status } = useQuery(
322 reactive({
323 queryKey: key2,
324 queryFn: dependentQueryFn,
325 enabled,
326 }),
327 )
328β
329 expect(data.value).toBeUndefined()
330 expect(fetchStatus.value).toBe('idle')
331 expect(dependentQueryFn).not.toHaveBeenCalled()
332 await vi.advanceTimersByTimeAsync(0)
333 expect(data.value).toBe('Some data')
334 expect(fetchStatus.value).toBe('fetching')
335 await vi.advanceTimersByTimeAsync(10)
336 expect(fetchStatus.value).toBe('idle')
337 expect(status.value).toBe('success')
338 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
339 expect(dependentQueryFn).toHaveBeenCalledWith(
340 expect.objectContaining({ queryKey: key2 }),
341 )
342 })
343β
344 it('should stop listening to changes on onScopeDispose', async () => {
345 const key = createKey()
346 const queryClient = useQueryClient()
347 const onScopeDisposeMock = vi.mocked(onScopeDispose)
348 onScopeDisposeMock.mockImplementationOnce((fn) => fn())
349β
350 const { status } = useQuery({
351 queryKey: key,
352 queryFn: () => sleep(0).then(() => 'Some data'),
353 })
354β
355 expect(status.value).toBe('pending')
356 await vi.advanceTimersByTimeAsync(0)
357 expect(queryClient.getQueryData(key)).toBe('Some data')
358 expect(status.value).toBe('pending')
359 await vi.advanceTimersByTimeAsync(0)
360 expect(status.value).toBe('pending')
361 })
362β
363 it('should use the current value for the queryKey when refetch is called', async () => {
364 const key = createKey()
365 const queryFn = vi.fn<() => string>(() => 'foo')
366 const keyRef = ref('key11')
367 const query = useQuery({
368 queryKey: [...key, keyRef],
369 queryFn,
370 enabled: false,
371 })
372β
373 expect(queryFn).not.toHaveBeenCalled()
374β
375 await query.refetch()
376 expect(queryFn).toHaveBeenCalledTimes(1)
377 expect(queryFn).toHaveBeenNthCalledWith(
378 1,
379 expect.objectContaining({
380 queryKey: [...key, 'key11'],
381 }),
382 )
383β
384 keyRef.value = 'key12'
385 await query.refetch()
386 expect(queryFn).toHaveBeenCalledTimes(2)
387 expect(queryFn).toHaveBeenNthCalledWith(
388 2,
389 expect.objectContaining({
390 queryKey: [...key, 'key12'],
391 }),
392 )
393β
394 keyRef.value = 'key13'
395 await query.state.refetch()
396 expect(queryFn).toHaveBeenCalledTimes(3)
397 expect(queryFn).toHaveBeenNthCalledWith(
398 3,
399 expect.objectContaining({
400 queryKey: [...key, 'key13'],
401 }),
402 )
403 })
404β
405 it.runIf(isVue3)(
406 'should return deeply reactive and readonly data by default',
407 async () => {
408 const key = createKey()
409 const { data } = useQuery({
410 queryKey: key,
411 queryFn: () => sleep(10).then(() => ({ nested: { count: 0 } })),
412 })
413β
414 await vi.advanceTimersByTimeAsync(10)
415 expect(data.value).toStrictEqual({ nested: { count: 0 } })
416 expect(isReactive(data.value?.nested)).toBe(true)
417 expect(isReadonly(data.value?.nested)).toBe(true)
418 },
419 )
420β
421 it('should return data in a shallow ref when shallow is true', async () => {
422 const key = createKey()
423 const { data } = useQuery({
424 queryKey: key,
425 queryFn: () => sleep(10).then(() => ({ nested: { count: 0 } })),
426 shallow: true,
427 })
428β
429 await vi.advanceTimersByTimeAsync(10)
430 expect(data.value).toStrictEqual({ nested: { count: 0 } })
431 expect(isReactive(data.value?.nested)).toBe(false)
432 expect(isReadonly(data.value?.nested)).toBe(false)
433 })
434β
435 it('should be `enabled` to accept getter function', async () => {
436 const key = createKey()
437 const queryFn = vi.fn<() => string>(() => 'foo')
438 const checked = ref(false)
439β
440 useQuery({
441 queryKey: key,
442 queryFn,
443 enabled: () => checked.value,
444 })
445β
446 expect(queryFn).not.toHaveBeenCalled()
447β
448 checked.value = true
449 await vi.advanceTimersByTimeAsync(0)
450 expect(queryFn).toHaveBeenCalledWith(
451 expect.objectContaining({ queryKey: key }),
452 )
453 })
454β
455 it('should pass the query to an enabled callback instead of calling it as a getter', () => {
456 const key = createKey()
457 const queryFn = vi.fn<() => string>(() => 'foo')
458 const enabled = vi.fn<
459 (query: { queryKey: ReadonlyArray<unknown> }) => boolean
460 >((query) => Array.isArray(query.queryKey))
461β
462 useQuery({
463 queryKey: key,
464 queryFn,
465 enabled,
466 })
467β
468 expect(queryFn).toHaveBeenCalledTimes(1)
469 expect(enabled.mock.calls.length).toBeGreaterThan(0)
470 for (const call of enabled.mock.calls) {
471 expect(call).toHaveLength(1)
472 expect(call[0]).toStrictEqual(expect.objectContaining({ queryKey: key }))
473 }
474 })
475β
476 it('should allow getters for query keys', async () => {
477 const key = createKey()
478 const queryFn = vi.fn<() => string>(() => 'foo')
479 const key1 = ref('key1')
480 const key2 = ref('key2')
481β
482 useQuery({
483 queryKey: [...key, () => key1.value, () => key2.value],
484 queryFn,
485 })
486β
487 expect(queryFn).toHaveBeenCalledTimes(1)
488β
489 key1.value = 'key3'
490 await vi.advanceTimersByTimeAsync(0)
491 expect(queryFn).toHaveBeenCalledTimes(2)
492β
493 key2.value = 'key4'
494 await vi.advanceTimersByTimeAsync(0)
495 expect(queryFn).toHaveBeenCalledTimes(3)
496 })
497β
498 it('should allow arbitrarily nested getters for query keys', async () => {
499 const key = createKey()
500 const queryFn = vi.fn<() => string>(() => 'foo')
501 const key1 = ref('key1')
502 const key2 = ref('key2')
503 const key3 = ref('key3')
504 const key4 = ref('key4')
505 const key5 = ref('key5')
506β
507 useQuery({
508 queryKey: [
509 ...key,
510 key1,
511 () => key2.value,
512 { key: () => key3.value },
513 [{ foo: { bar: () => key4.value } }],
514 () => ({
515 foo: {
516 bar: {
517 baz: () => key5.value,
518 },
519 },
520 }),
521 ],
522 queryFn,
523 })
524β
525 expect(queryFn).toHaveBeenCalledTimes(1)
526β
527 key1.value = 'key1-updated'
528 await vi.advanceTimersByTimeAsync(0)
529 expect(queryFn).toHaveBeenCalledTimes(2)
530β
531 key2.value = 'key2-updated'
532 await vi.advanceTimersByTimeAsync(0)
533 expect(queryFn).toHaveBeenCalledTimes(3)
534β
535 key3.value = 'key3-updated'
536 await vi.advanceTimersByTimeAsync(0)
537 expect(queryFn).toHaveBeenCalledTimes(4)
538β
539 key4.value = 'key4-updated'
540 await vi.advanceTimersByTimeAsync(0)
541 expect(queryFn).toHaveBeenCalledTimes(5)
542β
543 key5.value = 'key5-updated'
544 await vi.advanceTimersByTimeAsync(0)
545 expect(queryFn).toHaveBeenCalledTimes(6)
546 })
547β
548 it('should allow a getter for the whole query key', async () => {
549 const key = createKey()
550 const queryFn = vi.fn<() => Promise<string>>(() =>
551 sleep(10).then(() => 'foo'),
552 )
553 const key1 = ref('key1')
554β
555 useQuery({
556 queryKey: () => [...key, key1.value],
557 queryFn,
558 })
559β
560 expect(queryFn).toHaveBeenCalledTimes(1)
561β
562 key1.value = 'key3'
563 await vi.advanceTimersByTimeAsync(10)
564 expect(queryFn).toHaveBeenCalledTimes(2)
565 })
566β
567 it('should derive data via select without changing what is cached', async () => {
568 const key = createKey()
569 const query = useQuery({
570 queryKey: key,
571 queryFn: () => sleep(10).then(() => ['a', 'b', 'c']),
572 select: (posts) => posts.length,
573 })
574β
575 await vi.advanceTimersByTimeAsync(10)
576 expect(query).toMatchObject({
577 status: { value: 'success' },
578 data: { value: 3 },
579 })
580β
581 const queryClient = useQueryClient()
582β
583 expect(queryClient.getQueryData(key)).toStrictEqual(['a', 'b', 'c'])
584 })
585β
586 it('should stay disabled until the dependent value is set', async () => {
587 const key = createKey()
588 const postId = ref<number>()
589 const queryFn = vi.fn<() => Promise<string>>(() =>
590 sleep(10).then(() => 'Some data'),
591 )
592β
593 const query = useQuery({
594 queryKey: [...key, postId],
595 queryFn,
596 enabled: () => postId.value != null,
597 })
598β
599 await vi.advanceTimersByTimeAsync(10)
600 expect(queryFn).not.toHaveBeenCalled()
601 expect(query).toMatchObject({ status: { value: 'pending' } })
602β
603 postId.value = 1
604 await vi.advanceTimersByTimeAsync(10)
605 expect(queryFn).toHaveBeenCalledTimes(1)
606 expect(query).toMatchObject({
607 status: { value: 'success' },
608 data: { value: 'Some data' },
609 })
610 })
611β
612 it('should skip the query while a computed queryFn resolves to skipToken, and run it once defined', async () => {
613 const key = createKey()
614 const postId = ref<number>()
615 const queryFn = vi.fn<() => Promise<string>>(() =>
616 sleep(10).then(() => 'Some data'),
617 )
618β
619 const query = useQuery({
620 queryKey: [...key, postId],
621 queryFn: computed(() => (postId.value != null ? queryFn : skipToken)),
622 })
623β
624 await vi.advanceTimersByTimeAsync(10)
625 expect(queryFn).not.toHaveBeenCalled()
626 expect(query).toMatchObject({ status: { value: 'pending' } })
627β
628 postId.value = 1
629 await vi.advanceTimersByTimeAsync(10)
630 expect(queryFn).toHaveBeenCalledTimes(1)
631 expect(query).toMatchObject({
632 status: { value: 'success' },
633 data: { value: 'Some data' },
634 })
635 })
636β
637 it('should seed from initialData and skip the loading state', () => {
638 const key = createKey()
639 const query = useQuery({
640 queryKey: key,
641 queryFn: () => sleep(10).then(() => 'data'),
642 initialData: 'initial',
643 })
644β
645 expect(query).toMatchObject({
646 status: { value: 'success' },
647 data: { value: 'initial' },
648 })
649 })
650β
651 it('should still fetch in the background and replace initialData with the fetched value', async () => {
652 const key = createKey()
653 const queryFn = vi.fn<() => Promise<string>>(() =>
654 sleep(10).then(() => 'data'),
655 )
656β
657 const query = useQuery({
658 queryKey: key,
659 queryFn,
660 initialData: 'initial',
661 })
662β
663 await vi.advanceTimersByTimeAsync(10)
664 expect(queryFn).toHaveBeenCalledTimes(1)
665 expect(query).toMatchObject({
666 status: { value: 'success' },
667 data: { value: 'data' },
668 })
669 })
670β
671 it('should keep initialData visible alongside the error when a refetch fails', async () => {
672 const key = createKey()
673β
674 const query = useQuery({
675 queryKey: key,
676 queryFn: () =>
677 sleep(10).then(() => Promise.reject(new Error('Some error'))),
678 initialData: 'initial',
679 retry: false,
680 })
681β
682 expect(query).toMatchObject({
683 status: { value: 'success' },
684 data: { value: 'initial' },
685 isError: { value: false },
686 })
687 await vi.advanceTimersByTimeAsync(10)
688 expect(query).toMatchObject({
689 status: { value: 'error' },
690 data: { value: 'initial' },
691 isError: { value: true },
692 })
693 })
694β
695 it('should keep the previous page visible while the next page loads with keepPreviousData', async () => {
696 const key = createKey()
697 const page = ref(0)
698 const queryFn = vi.fn<(pageParam: number) => Promise<string>>(
699 (pageParam: number) => sleep(10).then(() => `page-${pageParam}`),
700 )
701β
702 const query = useQuery({
703 queryKey: [...key, page],
704 queryFn: () => queryFn(page.value),
705 placeholderData: keepPreviousData,
706 })
707β
708 await vi.advanceTimersByTimeAsync(10)
709 expect(query).toMatchObject({
710 data: { value: 'page-0' },
711 isPlaceholderData: { value: false },
712 })
713β
714 page.value = 1
715 await vi.advanceTimersByTimeAsync(0)
716 expect(query).toMatchObject({
717 data: { value: 'page-0' },
718 isPlaceholderData: { value: true },
719 })
720 await vi.advanceTimersByTimeAsync(10)
721 expect(query).toMatchObject({
722 data: { value: 'page-1' },
723 isPlaceholderData: { value: false },
724 })
725 })
726β
727 describe('throwOnError', () => {
728 it('should evaluate throwOnError when query is expected to throw', async () => {
729 const key = createKey()
730 const throwOnError =
731 vi.fn<
732 (
733 error: Error,
734 query: Query<unknown, Error, unknown, Array<string>>,
735 ) => boolean
736 >()
737 useQuery({
738 queryKey: key,
739 queryFn: () =>
740 sleep(0).then(() => Promise.reject(new Error('Some error'))),
741 retry: false,
742 throwOnError,
743 })
744β
745 await vi.advanceTimersByTimeAsync(0)
746 expect(throwOnError).toHaveBeenCalledTimes(1)
747 expect(throwOnError).toHaveBeenCalledWith(
748 Error('Some error'),
749 expect.objectContaining({
750 state: expect.objectContaining({ status: 'error' }),
751 }),
752 )
753 })
754 })
755β
756 describe('outside scope warning', () => {
757 it('should warn when used outside of setup function in development mode', () => {
758 vi.stubEnv('NODE_ENV', 'development')
759 const consoleWarnMock = vi
760 .spyOn(console, 'warn')
761 .mockImplementation(() => {})
762β
763 useQuery({
764 queryKey: createKey(),
765 queryFn: () => sleep(0).then(() => 'data'),
766 })
767β
768 expect(consoleWarnMock).toHaveBeenCalledWith(
769 '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.',
770 )
771 })
772 })
773β
774 describe('suspense', () => {
775 it('should return a Promise', () => {
776 const key = createKey()
777 const query = useQuery({
778 queryKey: key,
779 queryFn: () => sleep(0).then(() => 'Some data'),
780 })
781 const result = query.suspense()
782β
783 expect(result).toBeInstanceOf(Promise)
784 })
785β
786 it('should resolve after being enabled', async () => {
787 const key = createKey()
788 const queryFn = vi.fn<() => Promise<string>>(() =>
789 sleep(10).then(() => 'Some data'),
790 )
791 const onResolve =
792 vi.fn<(result: QueryObserverResult<string, Error>) => void>()
793 const isEnabled = ref(false)
794 const query = useQuery({
795 queryKey: key,
796 queryFn,
797 enabled: isEnabled,
798 })
799β
800 query.suspense().then(onResolve)
801 await vi.advanceTimersByTimeAsync(10)
802 expect(queryFn).not.toHaveBeenCalled()
803 expect(onResolve).not.toHaveBeenCalled()
804β
805 isEnabled.value = true
806 await vi.advanceTimersByTimeAsync(10)
807 expect(queryFn).toHaveBeenCalledTimes(1)
808 expect(onResolve).toHaveBeenCalledTimes(1)
809 expect(onResolve).toHaveBeenCalledWith(
810 expect.objectContaining({ data: 'Some data' }),
811 )
812 })
813β
814 it('should keep suspense pending while an enabled callback returns false', async () => {
815 const key = createKey()
816 const phase = ref('off')
817 const queryFn = vi.fn<() => Promise<string>>(() =>
818 sleep(10).then(() => 'Some data'),
819 )
820 const onResolve =
821 vi.fn<(result: QueryObserverResult<string, Error>) => void>()
822 const query = useQuery({
823 queryKey: [...key, phase],
824 queryFn,
825 enabled: (currentQuery) => currentQuery.queryKey.at(-1) === 'on',
826 })
827β
828 query.suspense().then(onResolve)
829 await vi.advanceTimersByTimeAsync(10)
830 expect(queryFn).not.toHaveBeenCalled()
831 expect(onResolve).not.toHaveBeenCalled()
832β
833 phase.value = 'on'
834 await vi.advanceTimersByTimeAsync(10)
835 expect(queryFn).toHaveBeenCalledTimes(1)
836 expect(onResolve).toHaveBeenCalledTimes(1)
837 expect(onResolve).toHaveBeenCalledWith(
838 expect.objectContaining({ data: 'Some data' }),
839 )
840 })
841β
842 it('should resolve immediately without refetching when the data is fresh', () => {
843 const key = createKey()
844 const queryFn = vi.fn<() => Promise<string>>(() =>
845 sleep(10).then(() => 'Some data'),
846 )
847β
848 const query = useQuery({
849 queryKey: key,
850 queryFn,
851 staleTime: 10000,
852 initialData: 'foo',
853 })
854β
855 return query.suspense().then(() => {
856 expect(queryFn).toHaveBeenCalledTimes(0)
857 })
858 })
859β
860 it('should not throw from suspense by default', async () => {
861 const key = createKey()
862 const query = useQuery({
863 queryKey: key,
864 queryFn: () =>
865 sleep(10).then(() => Promise.reject(new Error('Some error'))),
866 staleTime: 10000,
867 })
868β
869 const suspensePromise = query.suspense()
870 await vi.advanceTimersByTimeAsync(10)
871 await expect(suspensePromise).resolves.toMatchObject({
872 status: 'error',
873 isError: true,
874 })
875 })
876β
877 it('should throw from suspense when throwOnError is true', async ({
878 onTestFinished,
879 }) => {
880 const key = createKey()
881 const throwOnError = vi.fn<() => boolean>().mockReturnValue(true)
882 const query = useQuery({
883 queryKey: key,
884 queryFn: () =>
885 sleep(10).then(() => Promise.reject(new Error('Some error'))),
886 staleTime: 10000,
887 throwOnError,
888 })
889β
890 // The error watcher also throws, which Vue 3 surfaces as an unhandled rejection
891 process.on('unhandledRejection', noop)
892 onTestFinished(() => {
893 process.off('unhandledRejection', noop)
894 })
895β
896 await Promise.all([
897 expect(query.suspense()).rejects.toThrow('Some error'),
898 vi.advanceTimersByTimeAsync(10),
899 ])
900 expect(throwOnError).toHaveBeenCalledTimes(2)
901 expect(throwOnError).toHaveBeenNthCalledWith(
902 1,
903 Error('Some error'),
904 expect.objectContaining({
905 state: expect.objectContaining({ status: 'error' }),
906 }),
907 )
908 expect(throwOnError).toHaveBeenNthCalledWith(
909 2,
910 Error('Some error'),
911 expect.objectContaining({
912 state: expect.objectContaining({ status: 'error' }),
913 }),
914 )
915 })
916β
917 it('should release suspense when setQueryData is called while fetch is in-flight', async () => {
918 const key = createKey()
919β
920 const query = useQuery({
921 queryKey: key,
922 queryFn: () => sleep(10000).then(() => 'fetched'),
923 })
924β
925 const suspensePromise = query.suspense()
926β
927 const queryClient = useQueryClient()
928 queryClient.setQueryData(key, 'manual data')
929β
930 await vi.advanceTimersByTimeAsync(0)
931 const result = await suspensePromise
932 expect(result.data).toBe('manual data')
933 })
934β
935 it('should release suspense when streamedQuery receives first chunk', async () => {
936 const key = createKey()
937β
938 async function* numberGenerator() {
939 await sleep(10)
940 yield 'chunk1'
941 await sleep(10)
942 yield 'chunk2'
943 }
944β
945 const query = useQuery({
946 queryKey: key,
947 queryFn: experimental_streamedQuery({
948 streamFn: () => numberGenerator(),
949 }),
950 })
951β
952 const suspensePromise = query.suspense()
953 await vi.advanceTimersByTimeAsync(10)
954 const result = await suspensePromise
955 expect(result.data).toStrictEqual(['chunk1'])
956 })
957 })
958})