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