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