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

useQuery.test.ts

404 lines10.3 KB

1import {
2 computed,
3 getCurrentInstance,
4 onScopeDispose,
5 reactive,
6 ref,
7} from 'vue-demi'
8import { QueryObserver } from '@tanstack/query-core'
9​
10import { useQuery } from '../useQuery'
11import { parseQueryArgs, useBaseQuery } from '../useBaseQuery'
12import {
13 flushPromises,
14 getSimpleFetcherWithReturnData,
15 rejectFetcher,
16 simpleFetcher,
17} from './test-utils'
18​
19jest.mock('../useQueryClient')
20jest.mock('../useBaseQuery')
21​
22describe('useQuery', () => {
23 test('should properly execute query', () => {
24 useQuery(['key0'], simpleFetcher, { staleTime: 1000 })
25​
26 expect(useBaseQuery).toBeCalledWith(
27 QueryObserver,
28 ['key0'],
29 simpleFetcher,
30 {
31 staleTime: 1000,
32 },
33 )
34 })
35​
36 test('should return loading status initially', () => {
37 const query = useQuery(['key1'], simpleFetcher)
38​
39 expect(query).toMatchObject({
40 status: { value: 'loading' },
41 isLoading: { value: true },
42 isFetching: { value: true },
43 isStale: { value: true },
44 })
45 })
46​
47 test('should resolve to success and update reactive state: useQuery(key, dataFn)', async () => {
48 const query = useQuery(['key2'], getSimpleFetcherWithReturnData('result2'))
49​
50 await flushPromises()
51​
52 expect(query).toMatchObject({
53 status: { value: 'success' },
54 data: { value: 'result2' },
55 isLoading: { value: false },
56 isFetching: { value: false },
57 isFetched: { value: true },
58 isSuccess: { value: true },
59 })
60 })
61​
62 test('should resolve to success and update reactive state: useQuery(optionsObj)', async () => {
63 const query = useQuery({
64 queryKey: ['key31'],
65 queryFn: getSimpleFetcherWithReturnData('result31'),
66 enabled: true,
67 })
68​
69 await flushPromises()
70​
71 expect(query).toMatchObject({
72 status: { value: 'success' },
73 data: { value: 'result31' },
74 isLoading: { value: false },
75 isFetching: { value: false },
76 isFetched: { value: true },
77 isSuccess: { value: true },
78 })
79 })
80​
81 test('should resolve to success and update reactive state: useQuery(key, optionsObj)', async () => {
82 const query = useQuery(['key32'], {
83 queryFn: getSimpleFetcherWithReturnData('result32'),
84 enabled: true,
85 })
86​
87 await flushPromises()
88​
89 expect(query).toMatchObject({
90 status: { value: 'success' },
91 data: { value: 'result32' },
92 isLoading: { value: false },
93 isFetching: { value: false },
94 isFetched: { value: true },
95 isSuccess: { value: true },
96 })
97 })
98​
99 test('should reject and update reactive state', async () => {
100 const query = useQuery(['key3'], rejectFetcher)
101​
102 await flushPromises()
103​
104 expect(query).toMatchObject({
105 status: { value: 'error' },
106 data: { value: undefined },
107 error: { value: { message: 'Some error' } },
108 isLoading: { value: false },
109 isFetching: { value: false },
110 isFetched: { value: true },
111 isError: { value: true },
112 failureCount: { value: 1 },
113 failureReason: { value: { message: 'Some error' } },
114 })
115 })
116​
117 test('should update query on reactive options object change', async () => {
118 const spy = jest.fn()
119 const onSuccess = ref(() => {
120 // Noop
121 })
122 useQuery(
123 ['key6'],
124 simpleFetcher,
125 reactive({
126 onSuccess,
127 staleTime: 1000,
128 }),
129 )
130​
131 onSuccess.value = spy
132​
133 await flushPromises()
134​
135 expect(spy).toBeCalledTimes(1)
136 })
137​
138 test('should update query on reactive (Ref) key change', async () => {
139 const secondKeyRef = ref('key7')
140 const query = useQuery(['key6', secondKeyRef], simpleFetcher)
141​
142 await flushPromises()
143​
144 expect(query).toMatchObject({
145 status: { value: 'success' },
146 })
147​
148 secondKeyRef.value = 'key8'
149 await flushPromises()
150​
151 expect(query).toMatchObject({
152 status: { value: 'loading' },
153 data: { value: undefined },
154 })
155​
156 await flushPromises()
157​
158 expect(query).toMatchObject({
159 status: { value: 'success' },
160 })
161 })
162​
163 test("should update query when an option is passed as Ref and it's changed", async () => {
164 const enabled = ref(false)
165 const query = useQuery(['key9'], simpleFetcher, { enabled })
166​
167 await flushPromises()
168​
169 expect(query).toMatchObject({
170 fetchStatus: { value: 'idle' },
171 data: { value: undefined },
172 })
173​
174 enabled.value = true
175​
176 await flushPromises()
177​
178 expect(query).toMatchObject({
179 fetchStatus: { value: 'fetching' },
180 data: { value: undefined },
181 })
182​
183 await flushPromises()
184​
185 expect(query).toMatchObject({
186 status: { value: 'success' },
187 })
188 })
189​
190 test('should properly execute dependant queries', async () => {
191 const { data } = useQuery(['dependant1'], simpleFetcher)
192​
193 const enabled = computed(() => !!data.value)
194​
195 const dependentQueryFn = jest.fn().mockImplementation(simpleFetcher)
196 const { fetchStatus, status } = useQuery(
197 ['dependant2'],
198 dependentQueryFn,
199 reactive({
200 enabled,
201 }),
202 )
203​
204 expect(data.value).toStrictEqual(undefined)
205 expect(fetchStatus.value).toStrictEqual('idle')
206 expect(dependentQueryFn).not.toHaveBeenCalled()
207​
208 await flushPromises()
209​
210 expect(data.value).toStrictEqual('Some data')
211 expect(fetchStatus.value).toStrictEqual('fetching')
212​
213 await flushPromises()
214​
215 expect(fetchStatus.value).toStrictEqual('idle')
216 expect(status.value).toStrictEqual('success')
217 expect(dependentQueryFn).toHaveBeenCalledTimes(1)
218 expect(dependentQueryFn).toHaveBeenCalledWith(
219 expect.objectContaining({ queryKey: ['dependant2'] }),
220 )
221 })
222​
223 test('should stop listening to changes on onScopeDispose', async () => {
224 const onScopeDisposeMock = onScopeDispose as jest.MockedFunction<
225 typeof onScopeDispose
226 >
227 onScopeDisposeMock.mockImplementationOnce((fn) => fn())
228​
229 const { status } = useQuery(['onScopeDispose'], simpleFetcher)
230​
231 expect(status.value).toStrictEqual('loading')
232​
233 await flushPromises()
234​
235 expect(status.value).toStrictEqual('loading')
236​
237 await flushPromises()
238​
239 expect(status.value).toStrictEqual('loading')
240 })
241​
242 test('should use the current value for the queryKey when refetch is called', async () => {
243 const fetchFn = jest.fn()
244 const keyRef = ref('key11')
245 const query = useQuery({
246 queryKey: ['key10', keyRef],
247 queryFn: fetchFn,
248 enabled: false,
249 })
250​
251 expect(fetchFn).not.toHaveBeenCalled()
252 await query.refetch()
253 expect(fetchFn).toHaveBeenCalledTimes(1)
254 expect(fetchFn).toHaveBeenCalledWith(
255 expect.objectContaining({
256 queryKey: ['key10', 'key11'],
257 }),
258 )
259​
260 keyRef.value = 'key12'
261 await query.refetch()
262 expect(fetchFn).toHaveBeenCalledTimes(2)
263 expect(fetchFn).toHaveBeenCalledWith(
264 expect.objectContaining({
265 queryKey: ['key10', 'key12'],
266 }),
267 )
268 })
269​
270 test('should be `enabled` to accept getter function', async () => {
271 const fetchFn = jest.fn()
272 const checked = ref(false)
273​
274 useQuery({
275 queryKey: ['enabled'],
276 queryFn: fetchFn,
277 enabled: () => checked.value,
278 })
279​
280 expect(fetchFn).not.toHaveBeenCalled()
281​
282 checked.value = true
283​
284 await flushPromises()
285​
286 expect(fetchFn).toHaveBeenCalled()
287 })
288​
289 describe('errorBoundary', () => {
290 test('should evaluate useErrorBoundary when query is expected to throw', async () => {
291 const boundaryFn = jest.fn()
292 useQuery(['key0'], rejectFetcher, {
293 retry: false,
294 useErrorBoundary: boundaryFn,
295 })
296​
297 await flushPromises()
298​
299 expect(boundaryFn).toHaveBeenCalledTimes(1)
300 expect(boundaryFn).toHaveBeenCalledWith(
301 Error('Some error'),
302 expect.objectContaining({
303 state: expect.objectContaining({ status: 'error' }),
304 }),
305 )
306 })
307 })
308​
309 describe('parseQueryArgs', () => {
310 test('should unwrap refs arguments', () => {
311 const key = ref(['key'])
312 const fn = ref(simpleFetcher)
313 const options = ref({ enabled: ref(true) })
314​
315 const result = parseQueryArgs(key, fn, options)
316 const expected = {
317 queryKey: ['key'],
318 queryFn: simpleFetcher,
319 enabled: true,
320 }
321​
322 expect(result).toEqual(expected)
323 })
324​
325 test('should unwrap refs with fn in options', () => {
326 const key = ref(['key'])
327 const fn = ref(simpleFetcher)
328 const options = ref({ queryFn: fn, enabled: ref(true) })
329​
330 const result = parseQueryArgs(key, options)
331 const expected = {
332 queryKey: ['key'],
333 queryFn: simpleFetcher,
334 enabled: true,
335 }
336​
337 expect(result).toEqual(expected)
338 })
339​
340 test('should unwrap refs in options', () => {
341 const key = ref(['key'])
342 const fn = ref(simpleFetcher)
343 const options = ref({ queryKey: key, queryFn: fn, enabled: ref(true) })
344​
345 const result = parseQueryArgs(options)
346 const expected = {
347 queryKey: ['key'],
348 queryFn: simpleFetcher,
349 enabled: true,
350 }
351​
352 expect(result).toEqual(expected)
353 })
354 })
355​
356 describe('suspense', () => {
357 test('should return a Promise', () => {
358 const getCurrentInstanceSpy = getCurrentInstance as jest.Mock
359 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
360​
361 const query = useQuery(['suspense'], simpleFetcher)
362 const result = query.suspense()
363​
364 expect(result).toBeInstanceOf(Promise)
365 })
366​
367 test('should resolve after being enabled', () => {
368 const getCurrentInstanceSpy = getCurrentInstance as jest.Mock
369 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
370​
371 let afterTimeout = false
372 const isEnabeld = ref(false)
373 const query = useQuery(['suspense'], simpleFetcher, {
374 enabled: isEnabeld,
375 })
376​
377 setTimeout(() => {
378 afterTimeout = true
379 isEnabeld.value = true
380 }, 200)
381​
382 return query.suspense().then(() => {
383 expect(afterTimeout).toBe(true)
384 })
385 })
386​
387 test('should resolve immidiately when stale without refetching', () => {
388 const getCurrentInstanceSpy = getCurrentInstance as jest.Mock
389 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
390​
391 const fetcherSpy = jest.fn(() => simpleFetcher())
392​
393 // let afterTimeout = false;
394 const query = useQuery(['suspense'], simpleFetcher, {
395 staleTime: 10000,
396 initialData: 'foo',
397 })
398​
399 return query.suspense().then(() => {
400 expect(fetcherSpy).toHaveBeenCalledTimes(0)
401 })
402 })
403 })
404})