Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { computed, isReadonly, isVue3, onScopeDispose, ref } from 'vue-demi'
3import { skipToken } from '@tanstack/query-core'
4import { queryKey, sleep } from '@tanstack/query-test-utils'
5import { useQueries } from '../useQueries'
6import { useQueryClient } from '../useQueryClient'
7import { QueryClient } from '../queryClient'
8β
9vi.mock('../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 = queryKey()
23 const key2 = queryKey()
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 = queryKey()
54 const key2 = queryKey()
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 = queryKey()
86 const key2 = queryKey()
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 = queryKey()
119 const key2 = queryKey()
120 const key3 = queryKey()
121 const key4 = queryKey()
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.length).toEqual(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 = queryKey()
175 const key2 = queryKey()
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 = queryKey()
213 const key2 = queryKey()
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 = queryKey()
234 const key2 = queryKey()
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).toEqual({
265 combined: true,
266 res: [firstResult, secondResult],
267 })
268 })
269β
270 it('should be `enabled` to accept getter function', async () => {
271 const key = queryKey()
272 const queryFn = vi.fn(() => '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).toHaveBeenCalled()
290 })
291β
292 it('should skip a query while a computed queryFn resolves to skipToken, and run it once defined', async () => {
293 const key = queryKey()
294 const queryFn = vi.fn(() => sleep(10).then(() => 'foo'))
295 const checked = ref(false)
296β
297 useQueries({
298 queries: [
299 {
300 queryKey: key,
301 queryFn: computed(() => (checked.value ? queryFn : skipToken)),
302 },
303 ],
304 })
305β
306 expect(queryFn).not.toHaveBeenCalled()
307β
308 checked.value = true
309 await vi.advanceTimersByTimeAsync(10)
310 expect(queryFn).toHaveBeenCalled()
311 })
312β
313 it('should allow getters for query keys', async () => {
314 const key = queryKey()
315 const queryFn = vi.fn(() => 'foo')
316 const key1 = ref('key1')
317 const key2 = ref('key2')
318β
319 useQueries({
320 queries: [
321 {
322 queryKey: [...key, () => key1.value, () => key2.value],
323 queryFn,
324 },
325 ],
326 })
327β
328 expect(queryFn).toHaveBeenCalledTimes(1)
329β
330 key1.value = 'key3'
331 await vi.advanceTimersByTimeAsync(0)
332 expect(queryFn).toHaveBeenCalledTimes(2)
333β
334 key2.value = 'key4'
335 await vi.advanceTimersByTimeAsync(0)
336 expect(queryFn).toHaveBeenCalledTimes(3)
337 })
338β
339 it('should allow arbitrarily nested getters for query keys', async () => {
340 const key = queryKey()
341 const queryFn = vi.fn(() => 'foo')
342 const key1 = ref('key1')
343 const key2 = ref('key2')
344 const key3 = ref('key3')
345 const key4 = ref('key4')
346 const key5 = ref('key5')
347β
348 useQueries({
349 queries: [
350 {
351 queryKey: [
352 ...key,
353 key1,
354 () => key2.value,
355 { key: () => key3.value },
356 [{ foo: { bar: () => key4.value } }],
357 () => ({
358 foo: {
359 bar: {
360 baz: () => key5.value,
361 },
362 },
363 }),
364 ],
365 queryFn,
366 },
367 ],
368 })
369β
370 expect(queryFn).toHaveBeenCalledTimes(1)
371β
372 key1.value = 'key1-updated'
373 await vi.advanceTimersByTimeAsync(0)
374 expect(queryFn).toHaveBeenCalledTimes(2)
375β
376 key2.value = 'key2-updated'
377 await vi.advanceTimersByTimeAsync(0)
378 expect(queryFn).toHaveBeenCalledTimes(3)
379β
380 key3.value = 'key3-updated'
381 await vi.advanceTimersByTimeAsync(0)
382 expect(queryFn).toHaveBeenCalledTimes(4)
383β
384 key4.value = 'key4-updated'
385 await vi.advanceTimersByTimeAsync(0)
386 expect(queryFn).toHaveBeenCalledTimes(5)
387β
388 key5.value = 'key5-updated'
389 await vi.advanceTimersByTimeAsync(0)
390 expect(queryFn).toHaveBeenCalledTimes(6)
391 })
392β
393 it('should allow a getter for the whole query key', async () => {
394 const key = queryKey()
395 const queryFn = vi.fn(() => sleep(10).then(() => 'foo'))
396 const key1 = ref('key1')
397β
398 useQueries({
399 queries: [
400 {
401 queryKey: () => [...key, key1.value],
402 queryFn,
403 },
404 ],
405 })
406β
407 expect(queryFn).toHaveBeenCalledTimes(1)
408β
409 key1.value = 'key3'
410 await vi.advanceTimersByTimeAsync(10)
411 expect(queryFn).toHaveBeenCalledTimes(2)
412 })
413β
414 it.runIf(isVue3)('should return readonly results by default', async () => {
415 const key = queryKey()
416 const queriesState = useQueries({
417 queries: [
418 {
419 queryKey: key,
420 queryFn: () => sleep(10).then(() => ({ nested: { count: 0 } })),
421 },
422 ],
423 })
424β
425 await vi.advanceTimersByTimeAsync(10)
426 expect(queriesState.value[0].data).toEqual({ nested: { count: 0 } })
427 expect(isReadonly(queriesState.value[0])).toBe(true)
428 })
429β
430 it('should return results in a shallow ref when shallow is true', async () => {
431 const key = queryKey()
432 const queriesState = useQueries({
433 queries: [
434 {
435 queryKey: key,
436 queryFn: () => sleep(10).then(() => ({ nested: { count: 0 } })),
437 },
438 ],
439 shallow: true,
440 })
441β
442 await vi.advanceTimersByTimeAsync(10)
443 expect(queriesState.value[0].data).toEqual({ nested: { count: 0 } })
444 expect(isReadonly(queriesState.value[0])).toBe(false)
445 })
446β
447 it('should use the current value for the queryKey when refetch is called', async () => {
448 const key = queryKey()
449 const queryFn = vi.fn(() => 'foo')
450 const keyRef = ref('key11')
451 const queriesState = useQueries({
452 queries: [
453 {
454 queryKey: [...key, keyRef],
455 queryFn,
456 enabled: false,
457 },
458 ],
459 })
460β
461 expect(queryFn).not.toHaveBeenCalled()
462β
463 await queriesState.value[0].refetch()
464 expect(queryFn).toHaveBeenCalledTimes(1)
465 expect(queryFn).toHaveBeenNthCalledWith(
466 1,
467 expect.objectContaining({
468 queryKey: [...key, 'key11'],
469 }),
470 )
471β
472 keyRef.value = 'key12'
473 await queriesState.value[0].refetch()
474 expect(queryFn).toHaveBeenCalledTimes(2)
475 expect(queryFn).toHaveBeenNthCalledWith(
476 2,
477 expect.objectContaining({
478 queryKey: [...key, 'key12'],
479 }),
480 )
481 })
482β
483 it('should refetch only the specific query without affecting others', async () => {
484 const key1 = queryKey()
485 const key2 = queryKey()
486 let userCount = 0
487 let postCount = 0
488β
489 const queriesState = useQueries({
490 queries: [
491 {
492 queryKey: key1,
493 queryFn: () => sleep(10).then(() => `users-${++userCount}`),
494 },
495 {
496 queryKey: key2,
497 queryFn: () => sleep(20).then(() => `posts-${++postCount}`),
498 },
499 ],
500 })
501β
502 await vi.advanceTimersByTimeAsync(20)
503 expect(queriesState.value[0].data).toBe('users-1')
504 expect(queriesState.value[1].data).toBe('posts-1')
505β
506 queriesState.value[0].refetch()
507 await vi.advanceTimersByTimeAsync(10)
508 expect(queriesState.value[0].data).toBe('users-2')
509 expect(queriesState.value[1].data).toBe('posts-1')
510 expect(queriesState.value[1].isFetching).toBe(false)
511 })
512β
513 it('should warn when used outside of setup function in development mode', () => {
514 vi.stubEnv('NODE_ENV', 'development')
515 const consoleWarnMock = vi
516 .spyOn(console, 'warn')
517 .mockImplementation(() => {})
518β
519 try {
520 useQueries({
521 queries: [
522 {
523 queryKey: queryKey(),
524 queryFn: () => sleep(0).then(() => 'data'),
525 },
526 ],
527 })
528β
529 expect(consoleWarnMock).toHaveBeenCalledWith(
530 '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.',
531 )
532 } finally {
533 consoleWarnMock.mockRestore()
534 vi.unstubAllEnvs()
535 }
536 })
537β
538 it('should work with options getter and be reactive', async () => {
539 const key = queryKey()
540 const queryFn = vi.fn(() => 'foo')
541 const key1 = ref('key1')
542 const key2 = ref('key2')
543 const key3 = ref('key3')
544 const key4 = ref('key4')
545 const key5 = ref('key5')
546β
547 useQueries({
548 queries: () => [
549 {
550 queryKey: [
551 ...key,
552 key1,
553 key2.value,
554 { key: key3.value },
555 [{ foo: { bar: key4.value } }],
556 () => ({
557 foo: {
558 bar: {
559 baz: key5.value,
560 },
561 },
562 }),
563 ],
564 queryFn,
565 },
566 ],
567 })
568β
569 expect(queryFn).toHaveBeenCalledTimes(1)
570β
571 key1.value = 'key1-updated'
572 await vi.advanceTimersByTimeAsync(0)
573 expect(queryFn).toHaveBeenCalledTimes(2)
574β
575 key2.value = 'key2-updated'
576 await vi.advanceTimersByTimeAsync(0)
577 expect(queryFn).toHaveBeenCalledTimes(3)
578β
579 key3.value = 'key3-updated'
580 await vi.advanceTimersByTimeAsync(0)
581 expect(queryFn).toHaveBeenCalledTimes(4)
582β
583 key4.value = 'key4-updated'
584 await vi.advanceTimersByTimeAsync(0)
585 expect(queryFn).toHaveBeenCalledTimes(5)
586β
587 key5.value = 'key5-updated'
588 await vi.advanceTimersByTimeAsync(0)
589 expect(queryFn).toHaveBeenCalledTimes(6)
590 })
591})