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

queryClient.test.tsx

617 lines18.2 KB

1import { sleep, queryKey, mockConsoleError } from '../../react/tests/utils'
2import { QueryCache, QueryClient, QueryObserver } from '../..'
3​
4describe('queryClient', () => {
5 let queryClient: QueryClient
6 let queryCache: QueryCache
7​
8 beforeEach(() => {
9 queryClient = new QueryClient()
10 queryCache = queryClient.getQueryCache()
11 queryClient.mount()
12 })
13​
14 afterEach(() => {
15 queryClient.clear()
16 })
17​
18 describe('defaultOptions', () => {
19 test('should merge defaultOptions', async () => {
20 const key = queryKey()
21​
22 const queryFn = () => 'data'
23 const testClient = new QueryClient({
24 defaultOptions: { queries: { queryFn } },
25 })
26​
27 expect(() => testClient.prefetchQuery(key)).not.toThrow()
28 })
29​
30 test('should merge defaultOptions when query is added to cache', async () => {
31 const key = queryKey()
32​
33 const testClient = new QueryClient({
34 defaultOptions: {
35 queries: { cacheTime: Infinity },
36 },
37 })
38​
39 const fetchData = () => Promise.resolve(undefined)
40 await testClient.prefetchQuery(key, fetchData)
41 const newQuery = testClient.getQueryCache().find(key)
42 expect(newQuery?.options.cacheTime).toBe(Infinity)
43 })
44 })
45​
46 describe('setQueryDefaults', () => {
47 test('should not trigger a fetch', async () => {
48 const key = queryKey()
49 queryClient.setQueryDefaults(key, { queryFn: () => 'data' })
50 await sleep(1)
51 const data = queryClient.getQueryData(key)
52 expect(data).toBeUndefined()
53 })
54​
55 test('should be able to override defaults', async () => {
56 const key = queryKey()
57 queryClient.setQueryDefaults(key, { queryFn: () => 'data' })
58 const observer = new QueryObserver(queryClient, { queryKey: key })
59 const { data } = await observer.refetch()
60 expect(data).toBe('data')
61 })
62​
63 test('should match the query key partially', async () => {
64 const key = queryKey()
65 queryClient.setQueryDefaults([key], { queryFn: () => 'data' })
66 const observer = new QueryObserver(queryClient, {
67 queryKey: [key, 'a'],
68 })
69 const { data } = await observer.refetch()
70 expect(data).toBe('data')
71 })
72​
73 test('should not match if the query key is a subset', async () => {
74 const consoleMock = mockConsoleError()
75 const key = queryKey()
76 queryClient.setQueryDefaults([key, 'a'], { queryFn: () => 'data' })
77 const observer = new QueryObserver(queryClient, {
78 queryKey: [key],
79 retry: false,
80 enabled: false,
81 })
82 const { status } = await observer.refetch()
83 expect(status).toBe('error')
84 consoleMock.mockRestore()
85 })
86​
87 test('should also set defaults for observers', async () => {
88 const key = queryKey()
89 queryClient.setQueryDefaults(key, {
90 queryFn: () => 'data',
91 enabled: false,
92 })
93 const observer = new QueryObserver(queryClient, {
94 queryKey: [key],
95 })
96 expect(observer.getCurrentResult().status).toBe('idle')
97 })
98 })
99​
100 describe('setQueryData', () => {
101 test('should not crash if query could not be found', () => {
102 const key = queryKey()
103 const user = { userId: 1 }
104 expect(() => {
105 queryClient.setQueryData([key, user], (prevUser?: typeof user) => ({
106 ...prevUser!,
107 name: 'Edvin',
108 }))
109 }).not.toThrow()
110 })
111​
112 test('should not crash when variable is null', () => {
113 const key = queryKey()
114 queryClient.setQueryData([key, { userId: null }], 'Old Data')
115 expect(() => {
116 queryClient.setQueryData([key, { userId: null }], 'New Data')
117 }).not.toThrow()
118 })
119​
120 test('should use default options', () => {
121 const key = queryKey()
122 const testClient = new QueryClient({
123 defaultOptions: { queries: { queryKeyHashFn: () => 'someKey' } },
124 })
125 const testCache = testClient.getQueryCache()
126 testClient.setQueryData(key, 'data')
127 expect(testClient.getQueryData(key)).toBe('data')
128 expect(testCache.find(key)).toBe(testCache.get('someKey'))
129 })
130​
131 test('should create a new query if query was not found', () => {
132 const key = queryKey()
133 queryClient.setQueryData(key, 'bar')
134 expect(queryClient.getQueryData(key)).toBe('bar')
135 })
136​
137 test('should create a new query if query was not found', () => {
138 const key = queryKey()
139 queryClient.setQueryData(key, 'qux')
140 expect(queryClient.getQueryData(key)).toBe('qux')
141 })
142​
143 test('should accept an update function', () => {
144 const key = queryKey()
145​
146 const updater = jest.fn(oldData => `new data + ${oldData}`)
147​
148 queryClient.setQueryData(key, 'test data')
149 queryClient.setQueryData(key, updater)
150​
151 expect(updater).toHaveBeenCalled()
152 expect(queryCache.find(key)!.state.data).toEqual('new data + test data')
153 })
154 })
155​
156 describe('getQueryData', () => {
157 test('should return the query data if the query is found', () => {
158 const key = queryKey()
159 queryClient.setQueryData([key, 'id'], 'bar')
160 expect(queryClient.getQueryData([key, 'id'])).toBe('bar')
161 })
162​
163 test('should return undefined if the query is not found', () => {
164 const key = queryKey()
165 expect(queryClient.getQueryData(key)).toBeUndefined()
166 })
167​
168 test('should match exact by default', () => {
169 const key = queryKey()
170 queryClient.setQueryData([key, 'id'], 'bar')
171 expect(queryClient.getQueryData([key])).toBeUndefined()
172 })
173 })
174​
175 describe('fetchQuery', () => {
176 // https://github.com/tannerlinsley/react-query/issues/652
177 test('should not retry by default', async () => {
178 const consoleMock = mockConsoleError()
179​
180 const key = queryKey()
181​
182 await expect(
183 queryClient.fetchQuery(key, async () => {
184 throw new Error('error')
185 })
186 ).rejects.toEqual(new Error('error'))
187​
188 consoleMock.mockRestore()
189 })
190​
191 test('should return the cached data on cache hit', async () => {
192 const key = queryKey()
193​
194 const fetchFn = () => Promise.resolve('data')
195 const first = await queryClient.fetchQuery(key, fetchFn)
196 const second = await queryClient.fetchQuery(key, fetchFn)
197​
198 expect(second).toBe(first)
199 })
200​
201 test('should be able to fetch when cache time is set to 0 and then be removed', async () => {
202 const key1 = queryKey()
203 const result = await queryClient.fetchQuery(
204 key1,
205 async () => {
206 await sleep(10)
207 return 1
208 },
209 { cacheTime: 0 }
210 )
211 const result2 = queryClient.getQueryData(key1)
212 expect(result).toEqual(1)
213 expect(result2).toEqual(undefined)
214 })
215​
216 test('should keep a query in cache if cache time is Infinity', async () => {
217 const key1 = queryKey()
218 const result = await queryClient.fetchQuery(
219 key1,
220 async () => {
221 await sleep(10)
222 return 1
223 },
224 { cacheTime: Infinity }
225 )
226 const result2 = queryClient.getQueryData(key1)
227 expect(result).toEqual(1)
228 expect(result2).toEqual(1)
229 })
230​
231 test('should not force fetch', async () => {
232 const key = queryKey()
233​
234 queryClient.setQueryData(key, 'og')
235 const fetchFn = () => Promise.resolve('new')
236 const first = await queryClient.fetchQuery(key, fetchFn, {
237 initialData: 'initial',
238 staleTime: 100,
239 })
240 expect(first).toBe('og')
241 })
242​
243 test('should only fetch if the data is older then the given stale time', async () => {
244 const key = queryKey()
245​
246 let count = 0
247 const fetchFn = () => ++count
248​
249 queryClient.setQueryData(key, count)
250 const first = await queryClient.fetchQuery(key, fetchFn, {
251 staleTime: 100,
252 })
253 await sleep(11)
254 const second = await queryClient.fetchQuery(key, fetchFn, {
255 staleTime: 10,
256 })
257 const third = await queryClient.fetchQuery(key, fetchFn, {
258 staleTime: 10,
259 })
260 await sleep(11)
261 const fourth = await queryClient.fetchQuery(key, fetchFn, {
262 staleTime: 10,
263 })
264 expect(first).toBe(0)
265 expect(second).toBe(1)
266 expect(third).toBe(1)
267 expect(fourth).toBe(2)
268 })
269 })
270​
271 describe('fetchInfiniteQuery', () => {
272 test('should return infinite query data', async () => {
273 const key = queryKey()
274 const result = await queryClient.fetchInfiniteQuery(
275 key,
276 ({ pageParam = 10 }) => Number(pageParam)
277 )
278 const result2 = queryClient.getQueryData(key)
279​
280 const expected = {
281 pages: [10],
282 pageParams: [undefined],
283 }
284​
285 expect(result).toEqual(expected)
286 expect(result2).toEqual(expected)
287 })
288 })
289​
290 describe('prefetchInfiniteQuery', () => {
291 test('should return infinite query data', async () => {
292 const key = queryKey()
293​
294 await queryClient.prefetchInfiniteQuery(key, ({ pageParam = 10 }) =>
295 Number(pageParam)
296 )
297​
298 const result = queryClient.getQueryData(key)
299​
300 expect(result).toEqual({
301 pages: [10],
302 pageParams: [undefined],
303 })
304 })
305 })
306​
307 describe('prefetchQuery', () => {
308 test('should return undefined when an error is thrown', async () => {
309 const consoleMock = mockConsoleError()
310​
311 const key = queryKey()
312​
313 const result = await queryClient.prefetchQuery(
314 key,
315 async () => {
316 throw new Error('error')
317 },
318 {
319 retry: false,
320 }
321 )
322​
323 expect(result).toBeUndefined()
324 expect(consoleMock).toHaveBeenCalled()
325​
326 consoleMock.mockRestore()
327 })
328 })
329​
330 describe('removeQueries', () => {
331 test('should not crash when exact is provided', async () => {
332 const key = queryKey()
333​
334 const fetchFn = () => Promise.resolve('data')
335​
336 // check the query was added to the cache
337 await queryClient.prefetchQuery(key, fetchFn)
338 expect(queryCache.find(key)).toBeTruthy()
339​
340 // check the error doesn't occur
341 expect(() =>
342 queryClient.removeQueries({ queryKey: key, exact: true })
343 ).not.toThrow()
344​
345 // check query was successful removed
346 expect(queryCache.find(key)).toBeFalsy()
347 })
348 })
349​
350 describe('cancelQueries', () => {
351 test('should revert queries to their previous state', async () => {
352 const consoleMock = mockConsoleError()
353 const key1 = queryKey()
354 const key2 = queryKey()
355 const key3 = queryKey()
356 await queryClient.fetchQuery(key1, async () => {
357 return 'data'
358 })
359 try {
360 await queryClient.fetchQuery(key2, async () => {
361 return Promise.reject('err')
362 })
363 } catch {}
364 queryClient.fetchQuery(key1, async () => {
365 await sleep(1000)
366 return 'data2'
367 })
368 try {
369 queryClient.fetchQuery(key2, async () => {
370 await sleep(1000)
371 return Promise.reject('err2')
372 })
373 } catch {}
374 queryClient.fetchQuery(key3, async () => {
375 await sleep(1000)
376 return 'data3'
377 })
378 await sleep(10)
379 await queryClient.cancelQueries()
380 const state1 = queryClient.getQueryState(key1)
381 const state2 = queryClient.getQueryState(key2)
382 const state3 = queryClient.getQueryState(key3)
383 expect(state1).toMatchObject({
384 data: 'data',
385 status: 'success',
386 })
387 expect(state2).toMatchObject({
388 data: undefined,
389 error: 'err',
390 status: 'error',
391 })
392 expect(state3).toMatchObject({
393 data: undefined,
394 status: 'idle',
395 })
396 consoleMock.mockRestore()
397 })
398 })
399​
400 describe('refetchQueries', () => {
401 test('should refetch all queries when no arguments are given', async () => {
402 const key1 = queryKey()
403 const key2 = queryKey()
404 const queryFn1 = jest.fn()
405 const queryFn2 = jest.fn()
406 await queryClient.fetchQuery(key1, queryFn1)
407 await queryClient.fetchQuery(key2, queryFn2)
408 const observer1 = new QueryObserver(queryClient, {
409 queryKey: key1,
410 enabled: false,
411 })
412 const observer2 = new QueryObserver(queryClient, {
413 queryKey: key1,
414 enabled: false,
415 })
416 observer1.subscribe()
417 observer2.subscribe()
418 await queryClient.refetchQueries()
419 observer1.destroy()
420 observer2.destroy()
421 expect(queryFn1).toHaveBeenCalledTimes(2)
422 expect(queryFn2).toHaveBeenCalledTimes(2)
423 })
424​
425 test('should be able to refetch all fresh queries', async () => {
426 const key1 = queryKey()
427 const key2 = queryKey()
428 const queryFn1 = jest.fn()
429 const queryFn2 = jest.fn()
430 await queryClient.fetchQuery(key1, queryFn1)
431 await queryClient.fetchQuery(key2, queryFn2)
432 const observer = new QueryObserver(queryClient, {
433 queryKey: key1,
434 queryFn: queryFn1,
435 staleTime: Infinity,
436 })
437 const unsubscribe = observer.subscribe()
438 await queryClient.refetchQueries({ active: true, stale: false })
439 unsubscribe()
440 expect(queryFn1).toHaveBeenCalledTimes(2)
441 expect(queryFn2).toHaveBeenCalledTimes(1)
442 })
443​
444 test('should be able to refetch all stale queries', async () => {
445 const key1 = queryKey()
446 const key2 = queryKey()
447 const queryFn1 = jest.fn()
448 const queryFn2 = jest.fn()
449 await queryClient.fetchQuery(key1, queryFn1)
450 await queryClient.fetchQuery(key2, queryFn2)
451 const observer = new QueryObserver(queryClient, {
452 queryKey: key1,
453 queryFn: queryFn1,
454 })
455 const unsubscribe = observer.subscribe()
456 queryClient.invalidateQueries(key1)
457 await queryClient.refetchQueries({ stale: true })
458 unsubscribe()
459 expect(queryFn1).toHaveBeenCalledTimes(2)
460 expect(queryFn2).toHaveBeenCalledTimes(1)
461 })
462​
463 test('should be able to refetch all stale and active queries', async () => {
464 const key1 = queryKey()
465 const key2 = queryKey()
466 const queryFn1 = jest.fn()
467 const queryFn2 = jest.fn()
468 await queryClient.fetchQuery(key1, queryFn1)
469 await queryClient.fetchQuery(key2, queryFn2)
470 queryClient.invalidateQueries(key1)
471 const observer = new QueryObserver(queryClient, {
472 queryKey: key1,
473 queryFn: queryFn1,
474 })
475 const unsubscribe = observer.subscribe()
476 await queryClient.refetchQueries({ active: true, stale: true })
477 unsubscribe()
478 expect(queryFn1).toHaveBeenCalledTimes(2)
479 expect(queryFn2).toHaveBeenCalledTimes(1)
480 })
481​
482 test('should be able to refetch all active and inactive queries', async () => {
483 const key1 = queryKey()
484 const key2 = queryKey()
485 const queryFn1 = jest.fn()
486 const queryFn2 = jest.fn()
487 await queryClient.fetchQuery(key1, queryFn1)
488 await queryClient.fetchQuery(key2, queryFn2)
489 const observer = new QueryObserver(queryClient, {
490 queryKey: key1,
491 queryFn: queryFn1,
492 staleTime: Infinity,
493 })
494 const unsubscribe = observer.subscribe()
495 await queryClient.refetchQueries()
496 unsubscribe()
497 expect(queryFn1).toHaveBeenCalledTimes(2)
498 expect(queryFn2).toHaveBeenCalledTimes(2)
499 })
500​
501 test('should be able to refetch all active and inactive queries', async () => {
502 const key1 = queryKey()
503 const key2 = queryKey()
504 const queryFn1 = jest.fn()
505 const queryFn2 = jest.fn()
506 await queryClient.fetchQuery(key1, queryFn1)
507 await queryClient.fetchQuery(key2, queryFn2)
508 const observer = new QueryObserver(queryClient, {
509 queryKey: key1,
510 queryFn: queryFn1,
511 staleTime: Infinity,
512 })
513 const unsubscribe = observer.subscribe()
514 await queryClient.refetchQueries({ active: true, inactive: true })
515 unsubscribe()
516 expect(queryFn1).toHaveBeenCalledTimes(2)
517 expect(queryFn2).toHaveBeenCalledTimes(2)
518 })
519 })
520​
521 describe('invalidateQueries', () => {
522 test('should not refetch inactive queries by default', async () => {
523 const key1 = queryKey()
524 const key2 = queryKey()
525 const queryFn1 = jest.fn()
526 const queryFn2 = jest.fn()
527 await queryClient.fetchQuery(key1, queryFn1)
528 await queryClient.fetchQuery(key2, queryFn2)
529 const observer = new QueryObserver(queryClient, {
530 queryKey: key1,
531 enabled: false,
532 staleTime: Infinity,
533 })
534 const unsubscribe = observer.subscribe()
535 queryClient.invalidateQueries(key1)
536 unsubscribe()
537 expect(queryFn1).toHaveBeenCalledTimes(1)
538 expect(queryFn2).toHaveBeenCalledTimes(1)
539 })
540 })
541​
542 describe('resetQueries', () => {
543 test('should notify listeners when a query is reset', async () => {
544 const key = queryKey()
545​
546 const callback = jest.fn()
547​
548 await queryClient.prefetchQuery(key, () => 'data')
549​
550 queryCache.subscribe(callback)
551​
552 queryClient.resetQueries(key)
553​
554 expect(callback).toHaveBeenCalled()
555 })
556​
557 test('should reset query', async () => {
558 const key = queryKey()
559​
560 await queryClient.prefetchQuery(key, () => 'data')
561​
562 let state = queryClient.getQueryState(key)
563 expect(state?.data).toEqual('data')
564 expect(state?.status).toEqual('success')
565​
566 queryClient.resetQueries(key)
567​
568 state = queryClient.getQueryState(key)
569​
570 expect(state).toBeTruthy()
571 expect(state?.data).toBeUndefined()
572 expect(state?.status).toEqual('idle')
573 })
574​
575 test('should reset query data to initial data if set', async () => {
576 const key = queryKey()
577​
578 await queryClient.prefetchQuery(key, () => 'data', {
579 initialData: 'initial',
580 })
581​
582 let state = queryClient.getQueryState(key)
583 expect(state?.data).toEqual('data')
584​
585 queryClient.resetQueries(key)
586​
587 state = queryClient.getQueryState(key)
588​
589 expect(state).toBeTruthy()
590 expect(state?.data).toEqual('initial')
591 })
592​
593 test('should refetch all active queries', async () => {
594 const key1 = queryKey()
595 const key2 = queryKey()
596 const queryFn1 = jest.fn()
597 const queryFn2 = jest.fn()
598 const observer1 = new QueryObserver(queryClient, {
599 queryKey: key1,
600 queryFn: queryFn1,
601 enabled: true,
602 })
603 const observer2 = new QueryObserver(queryClient, {
604 queryKey: key2,
605 queryFn: queryFn2,
606 enabled: false,
607 })
608 observer1.subscribe()
609 observer2.subscribe()
610 await queryClient.resetQueries()
611 observer2.destroy()
612 observer1.destroy()
613 expect(queryFn1).toHaveBeenCalledTimes(2)
614 expect(queryFn2).toHaveBeenCalledTimes(0)
615 })
616 })
617})