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