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

queryCache.test.tsx

397 lines13.2 KB

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