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