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 describe('throwOnError', () => {
291 test('should evaluate throwOnError when query is expected to throw', async () => {
292 const boundaryFn = vi.fn()
293 useQuery({
294 queryKey: ['key0'],
295 queryFn: rejectFetcher,
296 retry: false,
297 throwOnError: boundaryFn,
298 })
299β
300 await flushPromises()
301β
302 expect(boundaryFn).toHaveBeenCalledTimes(1)
303 expect(boundaryFn).toHaveBeenCalledWith(
304 Error('Some error'),
305 expect.objectContaining({
306 state: expect.objectContaining({ status: 'error' }),
307 }),
308 )
309 })
310 })
311β
312 describe('suspense', () => {
313 test('should return a Promise', () => {
314 const getCurrentInstanceSpy = getCurrentInstance as Mock
315 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
316β
317 const query = useQuery({ queryKey: ['suspense'], queryFn: simpleFetcher })
318 const result = query.suspense()
319β
320 expect(result).toBeInstanceOf(Promise)
321 })
322β
323 test('should resolve after being enabled', () => {
324 const getCurrentInstanceSpy = getCurrentInstance as Mock
325 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
326β
327 let afterTimeout = false
328 const isEnabled = ref(false)
329 const query = useQuery({
330 queryKey: ['suspense2'],
331 queryFn: simpleFetcher,
332 enabled: isEnabled,
333 })
334β
335 setTimeout(() => {
336 afterTimeout = true
337 isEnabled.value = true
338 }, 200)
339β
340 return query.suspense().then(() => {
341 expect(afterTimeout).toBe(true)
342 })
343 })
344β
345 test('should resolve immediately when stale without refetching', () => {
346 const getCurrentInstanceSpy = getCurrentInstance as Mock
347 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
348β
349 const fetcherSpy = vi.fn(() => simpleFetcher())
350β
351 // let afterTimeout = false;
352 const query = useQuery({
353 queryKey: ['suspense3'],
354 queryFn: simpleFetcher,
355 staleTime: 10000,
356 initialData: 'foo',
357 })
358β
359 return query.suspense().then(() => {
360 expect(fetcherSpy).toHaveBeenCalledTimes(0)
361 })
362 })
363β
364 test('should not throw from suspense by default', async () => {
365 const getCurrentInstanceSpy = getCurrentInstance as Mock
366 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
367β
368 const query = useQuery({
369 queryKey: ['suspense4'],
370 queryFn: rejectFetcher,
371 staleTime: 10000,
372 })
373β
374 await flushPromises()
375β
376 expect(query).toMatchObject({
377 status: { value: 'error' },
378 isError: { value: true },
379 })
380 })
381β
382 test('should throw from suspense when throwOnError is true', async () => {
383 const getCurrentInstanceSpy = getCurrentInstance as Mock
384 getCurrentInstanceSpy.mockImplementation(() => ({ suspense: {} }))
385β
386 const boundaryFn = vi.fn()
387 const query = useQuery({
388 queryKey: ['suspense5'],
389 queryFn: rejectFetcher,
390 staleTime: 10000,
391 throwOnError: boundaryFn,
392 })
393β
394 await query.suspense()
395β
396 expect(boundaryFn).toHaveBeenCalledTimes(2)
397 expect(boundaryFn).toHaveBeenNthCalledWith(
398 1,
399 Error('Some error'),
400 expect.objectContaining({
401 state: expect.objectContaining({ status: 'error' }),
402 }),
403 )
404 expect(boundaryFn).toHaveBeenNthCalledWith(
405 2,
406 Error('Some error'),
407 expect.objectContaining({
408 state: expect.objectContaining({ status: 'error' }),
409 }),
410 )
411 })
412 })
413})