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