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

useQuery.test.ts

619 lines15.9 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 } 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})