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

useQuery.test.ts

617 lines15.8 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).toBeCalledWith(
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).toHaveBeenCalledWith(
336 expect.objectContaining({
337 queryKey: [...key, 'key11'],
338 }),
339 )
340​
341 keyRef.value = 'key12'
342 await query.refetch()
343 expect(fetchFn).toHaveBeenCalledTimes(2)
344 expect(fetchFn).toHaveBeenCalledWith(
345 expect.objectContaining({
346 queryKey: [...key, 'key12'],
347 }),
348 )
349 })
350​
351 it('should be `enabled` to accept getter function', async () => {
352 const key = queryKey()
353 const fetchFn = vi.fn(() => 'foo')
354 const checked = ref(false)
355​
356 useQuery({
357 queryKey: key,
358 queryFn: fetchFn,
359 enabled: () => checked.value,
360 })
361​
362 expect(fetchFn).not.toHaveBeenCalled()
363​
364 checked.value = true
365​
366 await vi.advanceTimersByTimeAsync(0)
367​
368 expect(fetchFn).toHaveBeenCalled()
369 })
370​
371 it('should allow getters for query keys', async () => {
372 const key = queryKey()
373 const fetchFn = vi.fn(() => 'foo')
374 const key1 = ref('key1')
375 const key2 = ref('key2')
376​
377 useQuery({
378 queryKey: [...key, () => key1.value, () => key2.value],
379 queryFn: fetchFn,
380 })
381​
382 expect(fetchFn).toHaveBeenCalledTimes(1)
383​
384 key1.value = 'key3'
385​
386 await vi.advanceTimersByTimeAsync(0)
387​
388 expect(fetchFn).toHaveBeenCalledTimes(2)
389​
390 key2.value = 'key4'
391​
392 await vi.advanceTimersByTimeAsync(0)
393​
394 expect(fetchFn).toHaveBeenCalledTimes(3)
395 })
396​
397 it('should allow arbitrarily nested getters for query keys', async () => {
398 const key = queryKey()
399 const fetchFn = vi.fn(() => 'foo')
400 const key1 = ref('key1')
401 const key2 = ref('key2')
402 const key3 = ref('key3')
403 const key4 = ref('key4')
404 const key5 = ref('key5')
405​
406 useQuery({
407 queryKey: [
408 ...key,
409 key1,
410 () => key2.value,
411 { key: () => key3.value },
412 [{ foo: { bar: () => key4.value } }],
413 () => ({
414 foo: {
415 bar: {
416 baz: () => key5.value,
417 },
418 },
419 }),
420 ],
421 queryFn: fetchFn,
422 })
423​
424 expect(fetchFn).toHaveBeenCalledTimes(1)
425​
426 key1.value = 'key1-updated'
427​
428 await vi.advanceTimersByTimeAsync(0)
429​
430 expect(fetchFn).toHaveBeenCalledTimes(2)
431​
432 key2.value = 'key2-updated'
433​
434 await vi.advanceTimersByTimeAsync(0)
435​
436 expect(fetchFn).toHaveBeenCalledTimes(3)
437​
438 key3.value = 'key3-updated'
439​
440 await vi.advanceTimersByTimeAsync(0)
441​
442 expect(fetchFn).toHaveBeenCalledTimes(4)
443​
444 key4.value = 'key4-updated'
445​
446 await vi.advanceTimersByTimeAsync(0)
447​
448 expect(fetchFn).toHaveBeenCalledTimes(5)
449​
450 key5.value = 'key5-updated'
451​
452 await vi.advanceTimersByTimeAsync(0)
453​
454 expect(fetchFn).toHaveBeenCalledTimes(6)
455 })
456​
457 describe('throwOnError', () => {
458 it('should evaluate throwOnError when query is expected to throw', async () => {
459 const key = queryKey()
460 const boundaryFn = vi.fn()
461 useQuery({
462 queryKey: key,
463 queryFn: () =>
464 sleep(0).then(() => Promise.reject(new Error('Some error'))),
465 retry: false,
466 throwOnError: boundaryFn,
467 })
468​
469 await vi.advanceTimersByTimeAsync(0)
470​
471 expect(boundaryFn).toHaveBeenCalledTimes(1)
472 expect(boundaryFn).toHaveBeenCalledWith(
473 Error('Some error'),
474 expect.objectContaining({
475 state: expect.objectContaining({ status: 'error' }),
476 }),
477 )
478 })
479 })
480​
481 describe('outside scope warning', () => {
482 it('should warn when used outside of setup function in development mode', () => {
483 vi.stubEnv('NODE_ENV', 'development')
484 const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
485​
486 try {
487 useQuery({
488 queryKey: queryKey(),
489 queryFn: () => sleep(0).then(() => 'data'),
490 })
491​
492 expect(warnSpy).toHaveBeenCalledWith(
493 '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.',
494 )
495 } finally {
496 warnSpy.mockRestore()
497 vi.unstubAllEnvs()
498 }
499 })
500 })
501​
502 describe('suspense', () => {
503 it('should return a Promise', () => {
504 const key = queryKey()
505 const getCurrentInstanceSpy = getCurrentInstance as Mock
506 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
507​
508 const query = useQuery({
509 queryKey: key,
510 queryFn: () => sleep(0).then(() => 'Some data'),
511 })
512 const result = query.suspense()
513​
514 expect(result).toBeInstanceOf(Promise)
515 })
516​
517 it('should resolve after being enabled', async () => {
518 const key = queryKey()
519 const getCurrentInstanceSpy = getCurrentInstance as Mock
520 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
521​
522 let afterTimeout = false
523 const isEnabled = ref(false)
524 const query = useQuery({
525 queryKey: key,
526 queryFn: () => sleep(0).then(() => 'Some data'),
527 enabled: isEnabled,
528 })
529​
530 setTimeout(() => {
531 afterTimeout = true
532 isEnabled.value = true
533 }, 200)
534​
535 query.suspense()
536​
537 await vi.advanceTimersByTimeAsync(200)
538​
539 expect(afterTimeout).toBe(true)
540 })
541​
542 it('should resolve immediately when stale without refetching', () => {
543 const key = queryKey()
544 const getCurrentInstanceSpy = getCurrentInstance as Mock
545 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
546​
547 const fetcherSpy = vi.fn(() => sleep(0).then(() => 'Some data'))
548​
549 // let afterTimeout = false;
550 const query = useQuery({
551 queryKey: key,
552 queryFn: () => sleep(0).then(() => 'Some data'),
553 staleTime: 10000,
554 initialData: 'foo',
555 })
556​
557 return query.suspense().then(() => {
558 expect(fetcherSpy).toHaveBeenCalledTimes(0)
559 })
560 })
561​
562 it('should not throw from suspense by default', async () => {
563 const key = queryKey()
564 const getCurrentInstanceSpy = getCurrentInstance as Mock
565 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
566​
567 const query = useQuery({
568 queryKey: key,
569 queryFn: () =>
570 sleep(0).then(() => Promise.reject(new Error('Some error'))),
571 staleTime: 10000,
572 })
573​
574 await vi.advanceTimersByTimeAsync(0)
575​
576 expect(query).toMatchObject({
577 status: { value: 'error' },
578 isError: { value: true },
579 })
580 })
581​
582 it('should throw from suspense when throwOnError is true', async () => {
583 const key = queryKey()
584 const getCurrentInstanceSpy = getCurrentInstance as Mock
585 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
586​
587 const boundaryFn = vi.fn()
588 const query = useQuery({
589 queryKey: key,
590 queryFn: () =>
591 sleep(0).then(() => Promise.reject(new Error('Some error'))),
592 staleTime: 10000,
593 throwOnError: boundaryFn,
594 })
595​
596 query.suspense()
597​
598 await vi.advanceTimersByTimeAsync(10000)
599​
600 expect(boundaryFn).toHaveBeenCalledTimes(2)
601 expect(boundaryFn).toHaveBeenNthCalledWith(
602 1,
603 Error('Some error'),
604 expect.objectContaining({
605 state: expect.objectContaining({ status: 'error' }),
606 }),
607 )
608 expect(boundaryFn).toHaveBeenNthCalledWith(
609 2,
610 Error('Some error'),
611 expect.objectContaining({
612 state: expect.objectContaining({ status: 'error' }),
613 }),
614 )
615 })
616 })
617})