Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { QueryCache, QueryClient, QueryObserver } from '..'
3import { createQueryClient, queryKey, sleep } from './utils'
4β
5describe('queryCache', () => {
6 let queryClient: QueryClient
7 let queryCache: QueryCache
8β
9 beforeEach(() => {
10 vi.useFakeTimers()
11 queryClient = createQueryClient()
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', async () => {
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 await vi.advanceTimersByTimeAsync(0)
28 expect(subscriber).toHaveBeenCalledWith({ query, type: 'added' })
29 unsubscribe()
30 })
31β
32 test('should notify listeners when new query is added', async () => {
33 const key = queryKey()
34 const callback = vi.fn()
35 queryCache.subscribe(callback)
36 queryClient.prefetchQuery({
37 queryKey: key,
38 queryFn: () => sleep(100).then(() => 'data'),
39 })
40 await vi.advanceTimersByTimeAsync(100)
41 expect(callback).toHaveBeenCalled()
42 })
43β
44 test('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.waitFor(() => 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 const query = queryCache.find({ queryKey: key })
91 await vi.advanceTimersByTimeAsync(100)
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 await vi.advanceTimersByTimeAsync(100)
133 expect(testCache.findAll().length).toBe(1)
134 testClient.prefetchQuery({
135 queryKey: ['key2'],
136 queryFn: () => sleep(100).then(() => 'data2'),
137 })
138 await vi.advanceTimersByTimeAsync(100)
139 expect(testCache.findAll().length).toBe(2)
140 testClient.prefetchQuery({
141 queryKey: ['key3'],
142 queryFn: () => sleep(100).then(() => 'data3'),
143 })
144 await vi.advanceTimersByTimeAsync(100)
145 expect(testCache.findAll().length).toBe(1)
146 expect(testCache.findAll()[0]!.state.data).toBe('data3')
147β
148 unsubscribe()
149 })
150 })
151β
152 describe('find', () => {
153 test('find should filter correctly', async () => {
154 const key = queryKey()
155 queryClient.prefetchQuery({
156 queryKey: key,
157 queryFn: () => sleep(100).then(() => 'data1'),
158 })
159 await vi.advanceTimersByTimeAsync(100)
160 const query = queryCache.find({ queryKey: key })!
161 expect(query).toBeDefined()
162 })
163β
164 test('find should filter correctly with exact set to false', async () => {
165 const key = queryKey()
166 queryClient.prefetchQuery({
167 queryKey: key,
168 queryFn: () => sleep(100).then(() => 'data1'),
169 })
170 await vi.advanceTimersByTimeAsync(100)
171 const query = queryCache.find({ queryKey: key, exact: false })!
172 expect(query).toBeDefined()
173 })
174 })
175β
176 describe('findAll', () => {
177 test('should filter correctly', async () => {
178 const key1 = queryKey()
179 const key2 = queryKey()
180 const keyFetching = queryKey()
181 queryClient.prefetchQuery({
182 queryKey: key1,
183 queryFn: () => sleep(100).then(() => 'data1'),
184 })
185 await vi.advanceTimersByTimeAsync(100)
186 queryClient.prefetchQuery({
187 queryKey: key2,
188 queryFn: () => sleep(100).then(() => 'data2'),
189 })
190 await vi.advanceTimersByTimeAsync(100)
191 queryClient.prefetchQuery({
192 queryKey: [{ a: 'a', b: 'b' }],
193 queryFn: () => sleep(100).then(() => 'data3'),
194 })
195 await vi.advanceTimersByTimeAsync(100)
196 queryClient.prefetchQuery({
197 queryKey: ['posts', 1],
198 queryFn: () => sleep(100).then(() => 'data4'),
199 })
200 await vi.advanceTimersByTimeAsync(100)
201 queryClient.invalidateQueries({ queryKey: key2 })
202 const query1 = queryCache.find({ queryKey: key1 })!
203 const query2 = queryCache.find({ queryKey: key2 })!
204 const query3 = queryCache.find({ queryKey: [{ a: 'a', b: 'b' }] })!
205 const query4 = queryCache.find({ queryKey: ['posts', 1] })!
206β
207 expect(queryCache.findAll({ queryKey: key1 })).toEqual([query1])
208 // wrapping in an extra array doesn't yield the same results anymore since v4 because keys need to be an array
209 expect(queryCache.findAll({ queryKey: [key1] })).toEqual([])
210 expect(queryCache.findAll()).toEqual([query1, query2, query3, query4])
211 expect(queryCache.findAll({})).toEqual([query1, query2, query3, query4])
212 expect(queryCache.findAll({ queryKey: key1, type: 'inactive' })).toEqual([
213 query1,
214 ])
215 expect(queryCache.findAll({ queryKey: key1, type: 'active' })).toEqual([])
216 expect(queryCache.findAll({ queryKey: key1, stale: true })).toEqual([])
217 expect(queryCache.findAll({ queryKey: key1, stale: false })).toEqual([
218 query1,
219 ])
220 expect(
221 queryCache.findAll({ queryKey: key1, stale: false, type: 'active' }),
222 ).toEqual([])
223 expect(
224 queryCache.findAll({
225 queryKey: key1,
226 stale: false,
227 type: 'inactive',
228 }),
229 ).toEqual([query1])
230 expect(
231 queryCache.findAll({
232 queryKey: key1,
233 stale: false,
234 type: 'inactive',
235 exact: true,
236 }),
237 ).toEqual([query1])
238β
239 expect(queryCache.findAll({ queryKey: key2 })).toEqual([query2])
240 expect(queryCache.findAll({ queryKey: key2, stale: undefined })).toEqual([
241 query2,
242 ])
243 expect(queryCache.findAll({ queryKey: key2, stale: true })).toEqual([
244 query2,
245 ])
246 expect(queryCache.findAll({ queryKey: key2, stale: false })).toEqual([])
247 expect(queryCache.findAll({ queryKey: [{ b: 'b' }] })).toEqual([query3])
248 expect(
249 queryCache.findAll({ queryKey: [{ a: 'a' }], exact: false }),
250 ).toEqual([query3])
251 expect(
252 queryCache.findAll({ queryKey: [{ a: 'a' }], exact: true }),
253 ).toEqual([])
254 expect(
255 queryCache.findAll({ queryKey: [{ a: 'a', b: 'b' }], exact: true }),
256 ).toEqual([query3])
257 expect(queryCache.findAll({ queryKey: [{ a: 'a', b: 'b' }] })).toEqual([
258 query3,
259 ])
260 expect(
261 queryCache.findAll({ queryKey: [{ a: 'a', b: 'b', c: 'c' }] }),
262 ).toEqual([])
263 expect(
264 queryCache.findAll({ queryKey: [{ a: 'a' }], stale: false }),
265 ).toEqual([query3])
266 expect(
267 queryCache.findAll({ queryKey: [{ a: 'a' }], stale: true }),
268 ).toEqual([])
269 expect(
270 queryCache.findAll({ queryKey: [{ a: 'a' }], type: 'active' }),
271 ).toEqual([])
272 expect(
273 queryCache.findAll({ queryKey: [{ a: 'a' }], type: 'inactive' }),
274 ).toEqual([query3])
275 expect(
276 queryCache.findAll({ predicate: (query) => query === query3 }),
277 ).toEqual([query3])
278 expect(queryCache.findAll({ queryKey: ['posts'] })).toEqual([query4])
279β
280 expect(queryCache.findAll({ fetchStatus: 'idle' })).toEqual([
281 query1,
282 query2,
283 query3,
284 query4,
285 ])
286 expect(
287 queryCache.findAll({ queryKey: key2, fetchStatus: undefined }),
288 ).toEqual([query2])
289β
290 queryClient.prefetchQuery({
291 queryKey: keyFetching,
292 queryFn: () => sleep(20).then(() => 'dataFetching'),
293 })
294 expect(queryCache.findAll({ fetchStatus: 'fetching' })).toEqual([
295 queryCache.find({ queryKey: keyFetching }),
296 ])
297 await vi.advanceTimersByTimeAsync(20)
298 expect(queryCache.findAll({ fetchStatus: 'fetching' })).toEqual([])
299 })
300β
301 test('should return all the queries when no filters are defined', async () => {
302 const key1 = queryKey()
303 const key2 = queryKey()
304 await queryClient.prefetchQuery({
305 queryKey: key1,
306 queryFn: () => 'data1',
307 })
308 await queryClient.prefetchQuery({
309 queryKey: key2,
310 queryFn: () => 'data2',
311 })
312 expect(queryCache.findAll().length).toBe(2)
313 })
314 })
315β
316 describe('QueryCacheConfig error callbacks', () => {
317 test('should call onError and onSettled when a query errors', async () => {
318 const key = queryKey()
319 const onSuccess = vi.fn()
320 const onSettled = vi.fn()
321 const onError = vi.fn()
322 const testCache = new QueryCache({ onSuccess, onError, onSettled })
323 const testClient = createQueryClient({ queryCache: testCache })
324 testClient.prefetchQuery({
325 queryKey: key,
326 queryFn: () => sleep(100).then(() => Promise.reject<unknown>('error')),
327 })
328 await vi.advanceTimersByTimeAsync(100)
329 const query = testCache.find({ queryKey: key })
330 expect(onError).toHaveBeenCalledWith('error', query)
331 expect(onError).toHaveBeenCalledTimes(1)
332 expect(onSuccess).not.toHaveBeenCalled()
333 expect(onSettled).toHaveBeenCalledTimes(1)
334 expect(onSettled).toHaveBeenCalledWith(undefined, 'error', query)
335 })
336 })
337β
338 describe('QueryCacheConfig success callbacks', () => {
339 test('should call onSuccess and onSettled when a query is successful', async () => {
340 const key = queryKey()
341 const onSuccess = vi.fn()
342 const onSettled = vi.fn()
343 const onError = vi.fn()
344 const testCache = new QueryCache({ onSuccess, onError, onSettled })
345 const testClient = createQueryClient({ queryCache: testCache })
346 testClient.prefetchQuery({
347 queryKey: key,
348 queryFn: () => sleep(100).then(() => ({ data: 5 })),
349 })
350 await vi.advanceTimersByTimeAsync(100)
351 const query = testCache.find({ queryKey: key })
352 expect(onSuccess).toHaveBeenCalledWith({ data: 5 }, query)
353 expect(onSuccess).toHaveBeenCalledTimes(1)
354 expect(onError).not.toHaveBeenCalled()
355 expect(onSettled).toHaveBeenCalledTimes(1)
356 expect(onSettled).toHaveBeenCalledWith({ data: 5 }, null, query)
357 })
358 })
359β
360 describe('QueryCache.add', () => {
361 test('should not try to add a query already added to the cache', async () => {
362 const key = queryKey()
363β
364 queryClient.prefetchQuery({
365 queryKey: key,
366 queryFn: () => sleep(100).then(() => 'data1'),
367 })
368 await vi.advanceTimersByTimeAsync(100)
369β
370 const query = queryCache.findAll()[0]!
371 const queryClone = Object.assign({}, query)
372β
373 queryCache.add(queryClone)
374 expect(queryCache.getAll().length).toEqual(1)
375 })
376 })
377})