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

queryCache.test.tsx

344 lines11.7 KB

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