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

mutationCache.test.tsx

424 lines11.8 KB

1import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2import { queryKey, sleep } from '@tanstack/query-test-utils'
3import { MutationCache, MutationObserver, QueryClient } from '..'
4import { executeMutation } from './utils'
5​
6describe('mutationCache', () => {
7 beforeEach(() => {
8 vi.useFakeTimers()
9 })
10​
11 afterEach(() => {
12 vi.useRealTimers()
13 })
14​
15 describe('MutationCacheConfig error callbacks', () => {
16 test('should call onError and onSettled when a mutation errors', async () => {
17 const key = queryKey()
18 const onError = vi.fn()
19 const onSuccess = vi.fn()
20 const onSettled = vi.fn()
21 const testCache = new MutationCache({ onError, onSuccess, onSettled })
22 const testClient = new QueryClient({ mutationCache: testCache })
23​
24 executeMutation(
25 testClient,
26 {
27 mutationKey: key,
28 mutationFn: () =>
29 sleep(10).then(() => Promise.reject(new Error('error'))),
30 onMutate: () => 'result',
31 },
32 'vars',
33 ).catch(() => undefined)
34 await vi.advanceTimersByTimeAsync(10)
35​
36 const mutation = testCache.getAll()[0]
37​
38 expect(onError).toHaveBeenCalledTimes(1)
39 expect(onError).toHaveBeenCalledWith(
40 new Error('error'),
41 'vars',
42 'result',
43 mutation,
44 {
45 client: testClient,
46 meta: undefined,
47 mutationKey: key,
48 },
49 )
50 expect(onSuccess).not.toHaveBeenCalled()
51 expect(onSettled).toHaveBeenCalledTimes(1)
52 expect(onSettled).toHaveBeenCalledWith(
53 undefined,
54 new Error('error'),
55 'vars',
56 'result',
57 mutation,
58 {
59 client: testClient,
60 meta: undefined,
61 mutationKey: key,
62 },
63 )
64 })
65​
66 test('should be awaited', async () => {
67 const key = queryKey()
68 const states: Array<number> = []
69 const onError = () =>
70 sleep(10).then(() => {
71 states.push(1)
72 states.push(2)
73 })
74 const onSettled = () =>
75 sleep(10).then(() => {
76 states.push(5)
77 states.push(6)
78 })
79​
80 const testCache = new MutationCache({ onError, onSettled })
81 const testClient = new QueryClient({ mutationCache: testCache })
82​
83 executeMutation(
84 testClient,
85 {
86 mutationKey: key,
87 mutationFn: () =>
88 sleep(10).then(() => Promise.reject(new Error('error'))),
89 onError: () =>
90 sleep(10).then(() => {
91 states.push(3)
92 states.push(4)
93 }),
94 onSettled: () =>
95 sleep(10).then(() => {
96 states.push(7)
97 states.push(8)
98 }),
99 },
100 'vars',
101 ).catch(() => undefined)
102 await vi.advanceTimersByTimeAsync(50)
103​
104 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
105 })
106 })
107​
108 describe('MutationCacheConfig success callbacks', () => {
109 test('should call onSuccess and onSettled when a mutation is successful', async () => {
110 const key = queryKey()
111 const onError = vi.fn()
112 const onSuccess = vi.fn()
113 const onSettled = vi.fn()
114 const testCache = new MutationCache({ onError, onSuccess, onSettled })
115 const testClient = new QueryClient({ mutationCache: testCache })
116​
117 executeMutation(
118 testClient,
119 {
120 mutationKey: key,
121 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
122 onMutate: () => 'result',
123 },
124 'vars',
125 )
126 await vi.advanceTimersByTimeAsync(10)
127​
128 const mutation = testCache.getAll()[0]
129​
130 expect(onSuccess).toHaveBeenCalledTimes(1)
131 expect(onSuccess).toHaveBeenCalledWith(
132 { data: 5 },
133 'vars',
134 'result',
135 mutation,
136 {
137 client: testClient,
138 meta: undefined,
139 mutationKey: key,
140 },
141 )
142 expect(onError).not.toHaveBeenCalled()
143 expect(onSettled).toHaveBeenCalledTimes(1)
144 expect(onSettled).toHaveBeenCalledWith(
145 { data: 5 },
146 null,
147 'vars',
148 'result',
149 mutation,
150 {
151 client: testClient,
152 meta: undefined,
153 mutationKey: key,
154 },
155 )
156 })
157​
158 test('should be awaited', async () => {
159 const key = queryKey()
160 const states: Array<number> = []
161 const onSuccess = () =>
162 sleep(10).then(() => {
163 states.push(1)
164 states.push(2)
165 })
166 const onSettled = () =>
167 sleep(10).then(() => {
168 states.push(5)
169 states.push(6)
170 })
171 const testCache = new MutationCache({ onSuccess, onSettled })
172 const testClient = new QueryClient({ mutationCache: testCache })
173​
174 executeMutation(
175 testClient,
176 {
177 mutationKey: key,
178 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
179 onSuccess: () =>
180 sleep(10).then(() => {
181 states.push(3)
182 states.push(4)
183 }),
184 onSettled: () =>
185 sleep(10).then(() => {
186 states.push(7)
187 states.push(8)
188 }),
189 },
190 'vars',
191 )
192 await vi.advanceTimersByTimeAsync(50)
193​
194 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
195 })
196 })
197​
198 describe('MutationCacheConfig.onMutate', () => {
199 test('should be called before a mutation executes', () => {
200 const key = queryKey()
201 const onMutate = vi.fn()
202 const testCache = new MutationCache({ onMutate })
203 const testClient = new QueryClient({ mutationCache: testCache })
204​
205 executeMutation(
206 testClient,
207 {
208 mutationKey: key,
209 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
210 onMutate: () => 'result',
211 },
212 'vars',
213 )
214​
215 const mutation = testCache.getAll()[0]
216​
217 expect(onMutate).toHaveBeenCalledWith('vars', mutation, {
218 client: testClient,
219 meta: undefined,
220 mutationKey: key,
221 })
222 })
223​
224 test('should be awaited', async () => {
225 const key = queryKey()
226 const states: Array<number> = []
227 const onMutate = () =>
228 sleep(10).then(() => {
229 states.push(1)
230 states.push(2)
231 })
232 const testCache = new MutationCache({ onMutate })
233 const testClient = new QueryClient({ mutationCache: testCache })
234​
235 executeMutation(
236 testClient,
237 {
238 mutationKey: key,
239 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
240 onMutate: () =>
241 sleep(10).then(() => {
242 states.push(3)
243 states.push(4)
244 }),
245 },
246 'vars',
247 )
248 await vi.advanceTimersByTimeAsync(20)
249​
250 expect(states).toEqual([1, 2, 3, 4])
251 })
252 })
253​
254 describe('find', () => {
255 test('should filter correctly', () => {
256 const testCache = new MutationCache()
257 const testClient = new QueryClient({ mutationCache: testCache })
258 const key = ['mutation', 'vars']
259​
260 executeMutation(
261 testClient,
262 {
263 mutationKey: key,
264 mutationFn: () => sleep(10).then(() => undefined),
265 },
266 'vars',
267 )
268​
269 const [mutation] = testCache.getAll()
270​
271 expect(testCache.find({ mutationKey: key })).toEqual(mutation)
272 expect(
273 testCache.find({ mutationKey: ['mutation'], exact: false }),
274 ).toEqual(mutation)
275 expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined)
276 expect(
277 testCache.find({
278 predicate: (m) => m.options.mutationKey?.[0] === key[0],
279 }),
280 ).toEqual(mutation)
281 })
282 })
283​
284 describe('findAll', () => {
285 test('should filter correctly', () => {
286 const testCache = new MutationCache()
287 const testClient = new QueryClient({ mutationCache: testCache })
288​
289 executeMutation(
290 testClient,
291 {
292 mutationKey: ['a', 1],
293 mutationFn: () => sleep(10).then(() => undefined),
294 },
295 1,
296 )
297 executeMutation(
298 testClient,
299 {
300 mutationKey: ['a', 2],
301 mutationFn: () => sleep(10).then(() => undefined),
302 },
303 2,
304 )
305 executeMutation(
306 testClient,
307 {
308 mutationKey: ['b'],
309 mutationFn: () => sleep(10).then(() => undefined),
310 },
311 3,
312 )
313​
314 const [mutation1, mutation2] = testCache.getAll()
315​
316 expect(
317 testCache.findAll({ mutationKey: ['a'], exact: false }),
318 ).toHaveLength(2)
319 expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1)
320 expect(
321 testCache.findAll({
322 predicate: (m) => m.options.mutationKey?.[1] === 2,
323 }),
324 ).toEqual([mutation2])
325 expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([])
326 })
327 })
328​
329 describe('garbage collection', () => {
330 test('should remove unused mutations after gcTime has elapsed', async () => {
331 const testCache = new MutationCache()
332 const testClient = new QueryClient({ mutationCache: testCache })
333 const onSuccess = vi.fn()
334​
335 executeMutation(
336 testClient,
337 {
338 mutationKey: ['a', 1],
339 gcTime: 10,
340 mutationFn: () => sleep(10).then(() => undefined),
341 onSuccess,
342 },
343 1,
344 )
345 await vi.advanceTimersByTimeAsync(10)
346​
347 expect(testCache.getAll()).toHaveLength(1)
348​
349 await vi.advanceTimersByTimeAsync(10)
350 expect(testCache.getAll()).toHaveLength(0)
351 expect(onSuccess).toHaveBeenCalledTimes(1)
352 })
353​
354 test('should not remove mutations if there are active observers', async () => {
355 const queryClient = new QueryClient()
356 const observer = new MutationObserver(queryClient, {
357 gcTime: 10,
358 mutationFn: (input: number) => sleep(10).then(() => input),
359 })
360 const unsubscribe = observer.subscribe(() => undefined)
361​
362 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
363​
364 observer.mutate(1)
365​
366 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
367​
368 await vi.advanceTimersByTimeAsync(10)
369 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
370​
371 unsubscribe()
372​
373 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
374​
375 await vi.advanceTimersByTimeAsync(10)
376 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
377 })
378​
379 test('should be garbage collected later when unsubscribed and mutation is pending', async () => {
380 const queryClient = new QueryClient()
381 const onSuccess = vi.fn()
382 const observer = new MutationObserver(queryClient, {
383 gcTime: 10,
384 mutationFn: () => sleep(10).then(() => 'data'),
385 onSuccess,
386 })
387 const unsubscribe = observer.subscribe(() => undefined)
388​
389 observer.mutate(1)
390​
391 unsubscribe()
392​
393 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
394​
395 await vi.advanceTimersByTimeAsync(10)
396 // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending
397 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
398​
399 await vi.advanceTimersByTimeAsync(10)
400 // should be removed after an additional gcTime wait
401 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
402 expect(onSuccess).toHaveBeenCalledTimes(1)
403 })
404​
405 test('should call callbacks even with gcTime 0 and mutation still pending', async () => {
406 const queryClient = new QueryClient()
407 const onSuccess = vi.fn()
408 const observer = new MutationObserver(queryClient, {
409 gcTime: 0,
410 mutationFn: () => sleep(10).then(() => 'data'),
411 onSuccess,
412 })
413 const unsubscribe = observer.subscribe(() => undefined)
414​
415 observer.mutate(1)
416​
417 unsubscribe()
418​
419 await vi.advanceTimersByTimeAsync(10)
420 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
421 expect(onSuccess).toHaveBeenCalledTimes(1)
422 })
423 })
424})