Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useQuery.test.ts

497 lines12.2 KB

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})