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