-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
queryCache.test.tsx
344 lines (312 loc) 路 11.7 KB
/
queryCache.test.tsx
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
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
import { waitFor } from '@testing-library/react'
import { QueryCache, QueryClient, QueryObserver } from '..'
import { createQueryClient, queryKey, sleep } from './utils'
describe('queryCache', () => {
let queryClient: QueryClient
let queryCache: QueryCache
beforeEach(() => {
queryClient = createQueryClient()
queryCache = queryClient.getQueryCache()
})
afterEach(() => {
queryClient.clear()
})
describe('subscribe', () => {
test('should pass the correct query', async () => {
const key = queryKey()
const subscriber = vi.fn()
const unsubscribe = queryCache.subscribe(subscriber)
queryClient.setQueryData(key, 'foo')
const query = queryCache.find({ queryKey: key })
await sleep(1)
expect(subscriber).toHaveBeenCalledWith({ query, type: 'added' })
unsubscribe()
})
test('should notify listeners when new query is added', async () => {
const key = queryKey()
const callback = vi.fn()
queryCache.subscribe(callback)
queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data' })
await sleep(100)
expect(callback).toHaveBeenCalled()
})
test('should notify query cache when a query becomes stale', async () => {
const key = queryKey()
const events: Array<string> = []
const unsubscribe = queryCache.subscribe((event) => {
events.push(event.type)
})
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => 'data',
staleTime: 10,
})
const unsubScribeObserver = observer.subscribe(vi.fn())
await waitFor(() => {
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
])
unsubscribe()
unsubScribeObserver()
})
test('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: () => 'data' })
const query = queryCache.find({ queryKey: key })
await sleep(100)
expect(callback).toHaveBeenCalledWith({ query, type: 'added' })
})
test('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: () => 'data',
initialData: 'initial',
})
await sleep(100)
expect(callback).toHaveBeenCalled()
})
test('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 })
await testClient.prefetchQuery({
queryKey: ['key1'],
queryFn: () => 'data1',
})
expect(testCache.findAll().length).toBe(1)
await testClient.prefetchQuery({
queryKey: ['key2'],
queryFn: () => 'data2',
})
expect(testCache.findAll().length).toBe(2)
await testClient.prefetchQuery({
queryKey: ['key3'],
queryFn: () => 'data3',
})
expect(testCache.findAll().length).toBe(1)
expect(testCache.findAll()[0]!.state.data).toBe('data3')
unsubscribe()
})
})
describe('find', () => {
test('find should filter correctly', async () => {
const key = queryKey()
await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data1' })
const query = queryCache.find({ queryKey: key })!
expect(query).toBeDefined()
})
test('find should filter correctly with exact set to false', async () => {
const key = queryKey()
await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data1' })
const query = queryCache.find({ queryKey: key, exact: false })!
expect(query).toBeDefined()
})
})
describe('findAll', () => {
test('should filter correctly', async () => {
const key1 = queryKey()
const key2 = queryKey()
const keyFetching = queryKey()
await queryClient.prefetchQuery({
queryKey: key1,
queryFn: () => 'data1',
})
await queryClient.prefetchQuery({
queryKey: key2,
queryFn: () => 'data2',
})
await queryClient.prefetchQuery({
queryKey: [{ a: 'a', b: 'b' }],
queryFn: () => 'data3',
})
await queryClient.prefetchQuery({
queryKey: ['posts', 1],
queryFn: () => 'data4',
})
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])
const promise = queryClient.prefetchQuery({
queryKey: keyFetching,
queryFn: async () => {
await sleep(20)
return 'dataFetching'
},
})
expect(queryCache.findAll({ fetchStatus: 'fetching' })).toEqual([
queryCache.find({ queryKey: keyFetching }),
])
await promise
expect(queryCache.findAll({ fetchStatus: 'fetching' })).toEqual([])
})
test('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', () => {
test('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 = createQueryClient({ queryCache: testCache })
await testClient.prefetchQuery({
queryKey: key,
queryFn: () => Promise.reject<unknown>('error'),
})
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', () => {
test('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 = createQueryClient({ queryCache: testCache })
await testClient.prefetchQuery({
queryKey: key,
queryFn: () => Promise.resolve({ data: 5 }),
})
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('QueryCache.add', () => {
test('should not try to add a query already added to the cache', async () => {
const key = queryKey()
await queryClient.prefetchQuery({ queryKey: key, queryFn: () => 'data1' })
const query = queryCache.findAll()[0]!
const queryClone = Object.assign({}, query)
queryCache.add(queryClone)
expect(queryCache.getAll().length).toEqual(1)
})
})
})