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