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