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

useQuery.test.ts

510 lines12.6 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 { 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})