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

queryCache.test.tsx

284 lines10.4 KB

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