Open History to see the last commit
1import {
2 sleep,
3 queryKey,
4 mockVisibilityState,
5 mockConsoleError,
6} from '../../react/tests/utils'
7import {
8 QueryCache,
9 QueryClient,
10 QueryObserver,
11 isCancelledError,
12 isError,
13 onlineManager,
14} from '../..'
15β
16describe('query', () => {
17 let queryClient: QueryClient
18 let queryCache: QueryCache
19β
20 beforeEach(() => {
21 queryClient = new QueryClient()
22 queryCache = queryClient.getQueryCache()
23 queryClient.mount()
24 })
25β
26 afterEach(() => {
27 queryClient.clear()
28 })
29β
30 test('should use the longest cache time it has seen', async () => {
31 const key = queryKey()
32 await queryClient.prefetchQuery(key, () => 'data', {
33 cacheTime: 100,
34 })
35 await queryClient.prefetchQuery(key, () => 'data', {
36 cacheTime: 200,
37 })
38 await queryClient.prefetchQuery(key, () => 'data', {
39 cacheTime: 10,
40 })
41 const query = queryCache.find(key)!
42 expect(query.cacheTime).toBe(200)
43 })
44β
45 it('should continue retry after focus regain and resolve all promises', async () => {
46 const key = queryKey()
47β
48 const originalVisibilityState = document.visibilityState
49β
50 // make page unfocused
51 mockVisibilityState('hidden')
52β
53 let count = 0
54 let result
55β
56 const promise = queryClient.fetchQuery(
57 key,
58 async () => {
59 count++
60β
61 if (count === 3) {
62 return `data${count}`
63 }
64β
65 throw new Error(`error${count}`)
66 },
67 {
68 retry: 3,
69 retryDelay: 1,
70 }
71 )
72β
73 promise.then(data => {
74 result = data
75 })
76β
77 // Check if we do not have a result
78 expect(result).toBeUndefined()
79β
80 // Check if the query is really paused
81 await sleep(50)
82 expect(result).toBeUndefined()
83β
84 // Reset visibilityState to original value
85 mockVisibilityState(originalVisibilityState)
86 window.dispatchEvent(new FocusEvent('focus'))
87β
88 // There should not be a result yet
89 expect(result).toBeUndefined()
90β
91 // By now we should have a value
92 await sleep(50)
93 expect(result).toBe('data3')
94 })
95β
96 it('should continue retry after reconnect and resolve all promises', async () => {
97 const key = queryKey()
98β
99 onlineManager.setOnline(false)
100β
101 let count = 0
102 let result
103β
104 const promise = queryClient.fetchQuery(
105 key,
106 async () => {
107 count++
108β
109 if (count === 3) {
110 return `data${count}`
111 }
112β
113 throw new Error(`error${count}`)
114 },
115 {
116 retry: 3,
117 retryDelay: 1,
118 }
119 )
120β
121 promise.then(data => {
122 result = data
123 })
124β
125 // Check if we do not have a result
126 expect(result).toBeUndefined()
127β
128 // Check if the query is really paused
129 await sleep(50)
130 expect(result).toBeUndefined()
131β
132 // Reset navigator to original value
133 onlineManager.setOnline(true)
134β
135 // There should not be a result yet
136 expect(result).toBeUndefined()
137β
138 // By now we should have a value
139 await sleep(50)
140 expect(result).toBe('data3')
141 })
142β
143 it('should throw a CancelledError when a paused query is cancelled', async () => {
144 const key = queryKey()
145β
146 const originalVisibilityState = document.visibilityState
147β
148 // make page unfocused
149 mockVisibilityState('hidden')
150β
151 let count = 0
152 let result
153β
154 const promise = queryClient.fetchQuery(
155 key,
156 async () => {
157 count++
158 throw new Error(`error${count}`)
159 },
160 {
161 retry: 3,
162 retryDelay: 1,
163 }
164 )
165β
166 promise.catch(data => {
167 result = data
168 })
169β
170 const query = queryCache.find(key)!
171β
172 // Check if the query is really paused
173 await sleep(50)
174 expect(result).toBeUndefined()
175β
176 // Cancel query
177 query.cancel()
178β
179 // Check if the error is set to the cancelled error
180 await sleep(0)
181 expect(isCancelledError(result)).toBe(true)
182β
183 // Reset visibilityState to original value
184 mockVisibilityState(originalVisibilityState)
185 window.dispatchEvent(new FocusEvent('focus'))
186 })
187β
188 test('should continue if cancellation is not supported', async () => {
189 const key = queryKey()
190β
191 queryClient.prefetchQuery(key, async () => {
192 await sleep(100)
193 return 'data'
194 })
195β
196 await sleep(10)
197β
198 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
199 const observer = new QueryObserver(queryClient, {
200 queryKey: key,
201 enabled: false,
202 })
203 const unsubscribe = observer.subscribe()
204 unsubscribe()
205β
206 await sleep(100)
207β
208 const query = queryCache.find(key)!
209β
210 expect(query.state).toMatchObject({
211 data: 'data',
212 status: 'success',
213 dataUpdateCount: 1,
214 })
215 })
216β
217 test('should not continue if cancellation is supported', async () => {
218 const key = queryKey()
219β
220 const cancel = jest.fn()
221β
222 queryClient.prefetchQuery(key, async () => {
223 const promise = new Promise((resolve, reject) => {
224 sleep(100).then(() => resolve('data'))
225 cancel.mockImplementation(() => {
226 reject(new Error('Cancelled'))
227 })
228 }) as any
229 promise.cancel = cancel
230 return promise
231 })
232β
233 await sleep(10)
234β
235 // Subscribe and unsubscribe to simulate cancellation because the last observer unsubscribed
236 const observer = new QueryObserver(queryClient, {
237 queryKey: key,
238 enabled: false,
239 })
240 const unsubscribe = observer.subscribe()
241 unsubscribe()
242β
243 await sleep(100)
244β
245 const query = queryCache.find(key)!
246β
247 expect(cancel).toHaveBeenCalled()
248 expect(query.state).toMatchObject({
249 data: undefined,
250 status: 'idle',
251 })
252 })
253β
254 test('should not continue if explicitly cancelled', async () => {
255 const key = queryKey()
256β
257 const queryFn = jest.fn()
258β
259 queryFn.mockImplementation(async () => {
260 await sleep(10)
261 throw new Error()
262 })
263β
264 let error
265β
266 const promise = queryClient.fetchQuery(key, queryFn, {
267 retry: 3,
268 retryDelay: 10,
269 })
270β
271 promise.catch(e => {
272 error = e
273 })
274β
275 const query = queryCache.find(key)!
276 query.cancel()
277β
278 await sleep(100)
279β
280 expect(queryFn).toHaveBeenCalledTimes(1)
281 expect(isCancelledError(error)).toBe(true)
282 })
283β
284 test('should not error if reset while loading', async () => {
285 const key = queryKey()
286β
287 const queryFn = jest.fn()
288β
289 queryFn.mockImplementation(async () => {
290 await sleep(10)
291 throw new Error()
292 })
293β
294 queryClient.fetchQuery(key, queryFn, {
295 retry: 3,
296 retryDelay: 10,
297 })
298β
299 // Ensure the query is loading
300 const query = queryCache.find(key)!
301 expect(query.state.status).toBe('loading')
302β
303 // Reset the query while it is loading
304 query.reset()
305β
306 await sleep(100)
307β
308 // The query should
309 expect(queryFn).toHaveBeenCalledTimes(1) // have been called,
310 expect(query.state.error).toBe(null) // not have an error, and
311 expect(query.state.status).toBe('idle') // not be loading any longer
312 })
313β
314 test('should be able to refetch a cancelled query', async () => {
315 const key = queryKey()
316β
317 const queryFn = jest.fn()
318β
319 queryFn.mockImplementation(async () => {
320 await sleep(50)
321 return 'data'
322 })
323β
324 queryClient.prefetchQuery(key, queryFn)
325 const query = queryCache.find(key)!
326 await sleep(10)
327 query.cancel()
328 await sleep(100)
329β
330 expect(queryFn).toHaveBeenCalledTimes(1)
331 expect(isCancelledError(query.state.error)).toBe(true)
332 const result = await query.fetch()
333 expect(result).toBe('data')
334 expect(query.state.error).toBe(null)
335 expect(queryFn).toHaveBeenCalledTimes(2)
336 })
337β
338 test('cancelling a resolved query should not have any effect', async () => {
339 const key = queryKey()
340 await queryClient.prefetchQuery(key, async () => 'data')
341 const query = queryCache.find(key)!
342 query.cancel()
343 await sleep(10)
344 expect(query.state.data).toBe('data')
345 })
346β
347 test('cancelling a rejected query should not have any effect', async () => {
348 const consoleMock = mockConsoleError()
349β
350 const key = queryKey()
351β
352 await queryClient.prefetchQuery(key, async () => {
353 throw new Error('error')
354 })
355 const query = queryCache.find(key)!
356 query.cancel()
357 await sleep(10)
358β
359 expect(isError(query.state.error)).toBe(true)
360 expect(isCancelledError(query.state.error)).toBe(false)
361β
362 consoleMock.mockRestore()
363 })
364β
365 test('the previous query status should be kept when refetching', async () => {
366 const consoleMock = mockConsoleError()
367 const key = queryKey()
368β
369 await queryClient.prefetchQuery(key, () => 'data')
370 const query = queryCache.find(key)!
371 expect(query.state.status).toBe('success')
372β
373 await queryClient.prefetchQuery(key, () => Promise.reject('reject'), {
374 retry: false,
375 })
376 expect(query.state.status).toBe('error')
377β
378 queryClient.prefetchQuery(
379 key,
380 async () => {
381 await sleep(10)
382 return Promise.reject('reject')
383 },
384 { retry: false }
385 )
386 expect(query.state.status).toBe('error')
387β
388 await sleep(100)
389 expect(query.state.status).toBe('error')
390β
391 consoleMock.mockRestore()
392 })
393β
394 test('queries with cacheTime 0 should be removed immediately after unsubscribing', async () => {
395 const consoleMock = mockConsoleError()
396 const key = queryKey()
397 let count = 0
398 const observer = new QueryObserver(queryClient, {
399 queryKey: key,
400 queryFn: () => {
401 count++
402 return 'data'
403 },
404 cacheTime: 0,
405 staleTime: Infinity,
406 })
407 const unsubscribe1 = observer.subscribe()
408 unsubscribe1()
409 await sleep(10)
410 const unsubscribe2 = observer.subscribe()
411 unsubscribe2()
412 await sleep(10)
413 expect(count).toBe(2)
414 expect(queryCache.find(key)).toBeUndefined()
415 consoleMock.mockRestore()
416 })
417β
418 test('should be garbage collected when unsubscribed to', async () => {
419 const key = queryKey()
420 const observer = new QueryObserver(queryClient, {
421 queryKey: key,
422 queryFn: async () => 'data',
423 cacheTime: 0,
424 })
425 expect(queryCache.find(key)).toBeDefined()
426 const unsubscribe = observer.subscribe()
427 expect(queryCache.find(key)).toBeDefined()
428 unsubscribe()
429 expect(queryCache.find(key)).toBeUndefined()
430 })
431β
432 test('should not be garbage collected unless there are no subscribers', async () => {
433 const key = queryKey()
434 const observer = new QueryObserver(queryClient, {
435 queryKey: key,
436 queryFn: async () => 'data',
437 cacheTime: 0,
438 })
439 expect(queryCache.find(key)).toBeDefined()
440 const unsubscribe = observer.subscribe()
441 await sleep(100)
442 expect(queryCache.find(key)).toBeDefined()
443 unsubscribe()
444 await sleep(100)
445 expect(queryCache.find(key)).toBeUndefined()
446 queryClient.setQueryData(key, 'data')
447 await sleep(100)
448 expect(queryCache.find(key)).toBeDefined()
449 })
450β
451 test('should return proper count of observers', async () => {
452 const key = queryKey()
453 const options = { queryKey: key, queryFn: async () => 'data' }
454 const observer = new QueryObserver(queryClient, options)
455 const observer2 = new QueryObserver(queryClient, options)
456 const observer3 = new QueryObserver(queryClient, options)
457 const query = queryCache.find(key)
458β
459 expect(query?.getObserversCount()).toEqual(0)
460β
461 const unsubscribe1 = observer.subscribe()
462 const unsubscribe2 = observer2.subscribe()
463 const unsubscribe3 = observer3.subscribe()
464 expect(query?.getObserversCount()).toEqual(3)
465β
466 unsubscribe3()
467 expect(query?.getObserversCount()).toEqual(2)
468β
469 unsubscribe2()
470 expect(query?.getObserversCount()).toEqual(1)
471β
472 unsubscribe1()
473 expect(query?.getObserversCount()).toEqual(0)
474 })
475})