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

useQuery.test.ts

364 lines9.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 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 isEnabeld = ref(false)
329 const query = useQuery({
330 queryKey: ['suspense'],
331 queryFn: simpleFetcher,
332 enabled: isEnabeld,
333 })
334​
335 setTimeout(() => {
336 afterTimeout = true
337 isEnabeld.value = true
338 }, 200)
339​
340 return query.suspense().then(() => {
341 expect(afterTimeout).toBe(true)
342 })
343 })
344​
345 test('should resolve immidiately 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: ['suspense'],
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})