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