Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { queryKey, sleep } from '@tanstack/query-test-utils'
3import { QueryCache, QueryClient, QueryObserver, hashKey, noop } from '..'
4β
5describe('queryCache', () => {
6 let queryClient: QueryClient
7 let queryCache: QueryCache
8β
9 beforeEach(() => {
10 vi.useFakeTimers()
11 queryClient = new QueryClient()
12 queryCache = queryClient.getQueryCache()
13 })
14β
15 afterEach(() => {
16 queryClient.clear()
17 vi.useRealTimers()
18 })
19β
20 describe('subscribe', () => {
21 it('should pass the correct query', () => {
22 const key = queryKey()
23 const subscriber = vi.fn()
24 const unsubscribe = queryCache.subscribe(subscriber)
25 queryClient.setQueryData(key, 'foo')
26 const query = queryCache.find({ queryKey: key })
27 expect(subscriber).toHaveBeenNthCalledWith(1, { query, type: 'added' })
28β
29 unsubscribe()
30 })
31β
32 it('should notify listeners when new query is added', async () => {
33 const key = queryKey()
34 const callback = vi.fn()
35 queryCache.subscribe(callback)
36 void queryClient
37 .query({
38 queryKey: key,
39 queryFn: () => sleep(100).then(() => 'data'),
40 })
41 .catch(noop)
42 await vi.advanceTimersByTimeAsync(100)
43 const query = queryCache.find({ queryKey: key })
44 expect(callback).toHaveBeenNthCalledWith(1, { query, type: 'added' })
45 })
46β
47 it('should notify query cache when a query becomes stale', async () => {
48 const key = queryKey()
49 const events: Array<string> = []
50 const queries: Array<unknown> = []
51 const unsubscribe = queryCache.subscribe((event) => {
52 events.push(event.type)
53 queries.push(event.query)
54 })
55β
56 const observer = new QueryObserver(queryClient, {
57 queryKey: key,
58 queryFn: () => 'data',
59 staleTime: 10,
60 })
61β
62 const unsubScribeObserver = observer.subscribe(vi.fn())
63 await vi.advanceTimersByTimeAsync(11)
64 expect(events.length).toBe(8)
65β
66 expect(events).toEqual([
67 'added', // 1. Query added -> loading
68 'observerResultsUpdated', // 2. Observer result updated -> loading
69 'observerAdded', // 3. Observer added
70 'observerResultsUpdated', // 4. Observer result updated -> fetching
71 'updated', // 5. Query updated -> fetching
72 'observerResultsUpdated', // 6. Observer result updated -> success
73 'updated', // 7. Query updated -> success
74 'observerResultsUpdated', // 8. Observer result updated -> stale
75 ])
76β
77 const cachedQuery = queryCache.find({ queryKey: key })
78 queries.forEach((query) => {
79 expect(query).toBe(cachedQuery)
80 })
81β
82 unsubscribe()
83 unsubScribeObserver()
84 })
85β
86 it('should include the queryCache and query when notifying listeners', async () => {
87 const key = queryKey()
88 const callback = vi.fn()
89 queryCache.subscribe(callback)
90 void queryClient
91 .query({
92 queryKey: key,
93 queryFn: () => sleep(100).then(() => 'data'),
94 })
95 .catch(noop)
96 await vi.advanceTimersByTimeAsync(100)
97 const query = queryCache.find({ queryKey: key })
98 expect(callback).toHaveBeenNthCalledWith(1, { query, type: 'added' })
99 })
100β
101 it('should notify subscribers when new query with initialData is added', async () => {
102 const key = queryKey()
103 const callback = vi.fn()
104 queryCache.subscribe(callback)
105 void queryClient
106 .query({
107 queryKey: key,
108 queryFn: () => sleep(100).then(() => 'data'),
109 initialData: 'initial',
110 })
111 .catch(noop)
112 await vi.advanceTimersByTimeAsync(100)
113 const query = queryCache.find({ queryKey: key })
114 expect(callback).toHaveBeenNthCalledWith(1, { query, type: 'added' })
115 })
116β
117 it('should be able to limit cache size', async () => {
118 const testCache = new QueryCache()
119β
120 const unsubscribe = testCache.subscribe((event) => {
121 if (event.type === 'added') {
122 if (testCache.getAll().length > 2) {
123 testCache
124 .findAll({
125 type: 'inactive',
126 predicate: (q) => q !== event.query,
127 })
128 .forEach((query) => {
129 testCache.remove(query)
130 })
131 }
132 }
133 })
134β
135 const testClient = new QueryClient({ queryCache: testCache })
136β
137 const key1 = queryKey()
138 const key2 = queryKey()
139 const key3 = queryKey()
140 void testClient
141 .query({
142 queryKey: key1,
143 queryFn: () => sleep(100).then(() => 'data1'),
144 })
145 .catch(noop)
146 expect(testCache.findAll().length).toBe(1)
147 void testClient
148 .query({
149 queryKey: key2,
150 queryFn: () => sleep(100).then(() => 'data2'),
151 })
152 .catch(noop)
153 expect(testCache.findAll().length).toBe(2)
154 void testClient
155 .query({
156 queryKey: key3,
157 queryFn: () => sleep(100).then(() => 'data3'),
158 })
159 .catch(noop)
160 await vi.advanceTimersByTimeAsync(100)
161 expect(testCache.findAll().length).toBe(1)
162 expect(testCache.findAll()[0]!.state.data).toBe('data3')
163β
164 unsubscribe()
165 })
166 })
167β
168 describe('find', () => {
169 it('should filter correctly with find', async () => {
170 const key = queryKey()
171 void queryClient
172 .query({
173 queryKey: key,
174 queryFn: () => sleep(100).then(() => 'data1'),
175 })
176 .catch(noop)
177 await vi.advanceTimersByTimeAsync(100)
178 const query = queryCache.find({ queryKey: key })!
179 expect(query.state.data).toBe('data1')
180 })
181β
182 it('should filter correctly with find when exact is set to false', async () => {
183 const key = queryKey()
184 void queryClient
185 .query({
186 queryKey: key,
187 queryFn: () => sleep(100).then(() => 'data1'),
188 })
189 .catch(noop)
190 await vi.advanceTimersByTimeAsync(100)
191 const query = queryCache.find({ queryKey: key, exact: false })!
192 expect(query.state.data).toBe('data1')
193 })
194 })
195β
196 describe('findAll', () => {
197 it('should filter correctly', async () => {
198 const key1 = queryKey()
199 const key2 = queryKey()
200 const keyFetching = queryKey()
201 void queryClient
202 .query({
203 queryKey: key1,
204 queryFn: () => sleep(100).then(() => 'data1'),
205 })
206 .catch(noop)
207 void queryClient
208 .query({
209 queryKey: key2,
210 queryFn: () => sleep(100).then(() => 'data2'),
211 })
212 .catch(noop)
213 void queryClient
214 .query({
215 queryKey: [{ a: 'a', b: 'b' }],
216 queryFn: () => sleep(100).then(() => 'data3'),
217 })
218 .catch(noop)
219 void queryClient
220 .query({
221 queryKey: ['posts', 1],
222 queryFn: () => sleep(100).then(() => 'data4'),
223 })
224 .catch(noop)
225 await vi.advanceTimersByTimeAsync(100)
226 queryClient.invalidateQueries({ queryKey: key2 })
227 const query1 = queryCache.find({ queryKey: key1 })!
228 const query2 = queryCache.find({ queryKey: key2 })!
229 const query3 = queryCache.find({ queryKey: [{ a: 'a', b: 'b' }] })!
230 const query4 = queryCache.find({ queryKey: ['posts', 1] })!
231β
232 expect(queryCache.findAll({ queryKey: key1 })).toEqual([query1])
233 // wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array
234 expect(queryCache.findAll({ queryKey: [key1] })).toEqual([])
235 expect(queryCache.findAll()).toEqual([query1, query2, query3, query4])
236 expect(queryCache.findAll({})).toEqual([query1, query2, query3, query4])
237 expect(queryCache.findAll({ queryKey: key1, type: 'inactive' })).toEqual([
238 query1,
239 ])
240 expect(queryCache.findAll({ queryKey: key1, type: 'active' })).toEqual([])
241 expect(queryCache.findAll({ queryKey: key1, stale: true })).toEqual([])
242 expect(queryCache.findAll({ queryKey: key1, stale: false })).toEqual([
243 query1,
244 ])
245 expect(
246 queryCache.findAll({ queryKey: key1, stale: false, type: 'active' }),
247 ).toEqual([])
248 expect(
249 queryCache.findAll({
250 queryKey: key1,
251 stale: false,
252 type: 'inactive',
253 }),
254 ).toEqual([query1])
255 expect(
256 queryCache.findAll({
257 queryKey: key1,
258 stale: false,
259 type: 'inactive',
260 exact: true,
261 }),
262 ).toEqual([query1])
263β
264 expect(queryCache.findAll({ queryKey: key2 })).toEqual([query2])
265 expect(queryCache.findAll({ queryKey: key2, stale: undefined })).toEqual([
266 query2,
267 ])
268 expect(queryCache.findAll({ queryKey: key2, stale: true })).toEqual([
269 query2,
270 ])
271 expect(queryCache.findAll({ queryKey: key2, stale: false })).toEqual([])
272 expect(queryCache.findAll({ queryKey: [{ b: 'b' }] })).toEqual([query3])
273 expect(
274 queryCache.findAll({ queryKey: [{ a: 'a' }], exact: false }),
275 ).toEqual([query3])
276 expect(
277 queryCache.findAll({ queryKey: [{ a: 'a' }], exact: true }),
278 ).toEqual([])
279 expect(
280 queryCache.findAll({ queryKey: [{ a: 'a', b: 'b' }], exact: true }),
281 ).toEqual([query3])
282 expect(queryCache.findAll({ queryKey: [{ a: 'a', b: 'b' }] })).toEqual([
283 query3,
284 ])
285 expect(
286 queryCache.findAll({ queryKey: [{ a: 'a', b: 'b', c: 'c' }] }),
287 ).toEqual([])
288 expect(
289 queryCache.findAll({ queryKey: [{ a: 'a' }], stale: false }),
290 ).toEqual([query3])
291 expect(
292 queryCache.findAll({ queryKey: [{ a: 'a' }], stale: true }),
293 ).toEqual([])
294 expect(
295 queryCache.findAll({ queryKey: [{ a: 'a' }], type: 'active' }),
296 ).toEqual([])
297 expect(
298 queryCache.findAll({ queryKey: [{ a: 'a' }], type: 'inactive' }),
299 ).toEqual([query3])
300 expect(
301 queryCache.findAll({ predicate: (query) => query === query3 }),
302 ).toEqual([query3])
303 expect(queryCache.findAll({ queryKey: ['posts'] })).toEqual([query4])
304β
305 expect(queryCache.findAll({ fetchStatus: 'idle' })).toEqual([
306 query1,
307 query2,
308 query3,
309 query4,
310 ])
311 expect(
312 queryCache.findAll({ queryKey: key2, fetchStatus: undefined }),
313 ).toEqual([query2])
314β
315 void queryClient
316 .query({
317 queryKey: keyFetching,
318 queryFn: () => sleep(20).then(() => 'dataFetching'),
319 })
320 .catch(noop)
321 expect(queryCache.findAll({ fetchStatus: 'fetching' })).toEqual([
322 queryCache.find({ queryKey: keyFetching }),
323 ])
324 await vi.advanceTimersByTimeAsync(20)
325 expect(queryCache.findAll({ fetchStatus: 'fetching' })).toEqual([])
326 })
327β
328 it('should return all the queries when no filters are defined', async () => {
329 const key1 = queryKey()
330 const key2 = queryKey()
331 await queryClient
332 .query({
333 queryKey: key1,
334 queryFn: () => 'data1',
335 })
336 .catch(noop)
337 await queryClient
338 .query({
339 queryKey: key2,
340 queryFn: () => 'data2',
341 })
342 .catch(noop)
343 expect(queryCache.findAll().length).toBe(2)
344 })
345 })
346β
347 describe('QueryCacheConfig error callbacks', () => {
348 it('should call onError and onSettled when a query errors', async () => {
349 const key = queryKey()
350 const onSuccess = vi.fn()
351 const onSettled = vi.fn()
352 const onError = vi.fn()
353 const testCache = new QueryCache({ onSuccess, onError, onSettled })
354 const testClient = new QueryClient({ queryCache: testCache })
355 void testClient
356 .query({
357 queryKey: key,
358 queryFn: () =>
359 sleep(100).then(() => Promise.reject<unknown>('error')),
360 })
361 .catch(noop)
362 await vi.advanceTimersByTimeAsync(100)
363 const query = testCache.find({ queryKey: key })
364 expect(onError).toHaveBeenCalledWith('error', query)
365 expect(onError).toHaveBeenCalledTimes(1)
366 expect(onSuccess).not.toHaveBeenCalled()
367 expect(onSettled).toHaveBeenCalledTimes(1)
368 expect(onSettled).toHaveBeenCalledWith(undefined, 'error', query)
369 })
370 })
371β
372 describe('QueryCacheConfig success callbacks', () => {
373 it('should call onSuccess and onSettled when a query is successful', async () => {
374 const key = queryKey()
375 const onSuccess = vi.fn()
376 const onSettled = vi.fn()
377 const onError = vi.fn()
378 const testCache = new QueryCache({ onSuccess, onError, onSettled })
379 const testClient = new QueryClient({ queryCache: testCache })
380 void testClient
381 .query({
382 queryKey: key,
383 queryFn: () => sleep(100).then(() => ({ data: 5 })),
384 })
385 .catch(noop)
386 await vi.advanceTimersByTimeAsync(100)
387 const query = testCache.find({ queryKey: key })
388 expect(onSuccess).toHaveBeenCalledWith({ data: 5 }, query)
389 expect(onSuccess).toHaveBeenCalledTimes(1)
390 expect(onError).not.toHaveBeenCalled()
391 expect(onSettled).toHaveBeenCalledTimes(1)
392 expect(onSettled).toHaveBeenCalledWith({ data: 5 }, null, query)
393 })
394 })
395β
396 describe('build', () => {
397 it('should compute queryHash from queryKey when queryHash is not provided', () => {
398 const key = queryKey()
399β
400 const query = queryCache.build(queryClient, {
401 queryKey: key,
402 })
403β
404 expect(query.queryHash).toBe(hashKey(key))
405 })
406β
407 it('should use provided queryHash instead of computing it', () => {
408 const key = queryKey()
409 const customHash = 'custom-hash'
410β
411 const query = queryCache.build(queryClient, {
412 queryKey: key,
413 queryHash: customHash,
414 })
415β
416 expect(query.queryHash).toBe(customHash)
417 expect(query.queryHash).not.toBe(hashKey(key))
418 })
419 })
420β
421 describe('QueryCache.remove', () => {
422 it('should be a no-op if the query is no longer the cached instance', () => {
423 const key = queryKey()
424β
425 const staleQuery = queryCache.build(queryClient, { queryKey: key })
426 queryCache.remove(staleQuery)
427β
428 const currentQuery = queryCache.build(queryClient, { queryKey: key })
429β
430 expect(currentQuery).not.toBe(staleQuery)
431 const subscriber = vi.fn()
432 const unsubscribe = queryCache.subscribe(subscriber)
433β
434 queryCache.remove(staleQuery)
435β
436 expect(queryCache.get(hashKey(key))).toBe(currentQuery)
437 expect(subscriber).not.toHaveBeenCalled()
438β
439 unsubscribe()
440 })
441 })
442β
443 describe('QueryCache.add', () => {
444 it('should not try to add a query already added to the cache', async () => {
445 const key = queryKey()
446β
447 void queryClient
448 .query({
449 queryKey: key,
450 queryFn: () => sleep(100).then(() => 'data1'),
451 })
452 .catch(noop)
453 await vi.advanceTimersByTimeAsync(100)
454β
455 const query = queryCache.findAll()[0]!
456 const queryClone = Object.assign({}, query)
457β
458 queryCache.add(queryClone)
459β
460 expect(queryCache.getAll().length).toEqual(1)
461 })
462 })
463})