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