Open History to see the last commit
1import { afterEach, beforeEach, describe, expect, it, 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 it('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 it('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 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
104 })
105 })
106β
107 describe('MutationCacheConfig success callbacks', () => {
108 it('should call onSuccess and onSettled when a mutation is successful', async () => {
109 const key = queryKey()
110 const onError = vi.fn()
111 const onSuccess = vi.fn()
112 const onSettled = vi.fn()
113 const testCache = new MutationCache({ onError, onSuccess, onSettled })
114 const testClient = new QueryClient({ mutationCache: testCache })
115β
116 executeMutation(
117 testClient,
118 {
119 mutationKey: key,
120 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
121 onMutate: () => 'result',
122 },
123 'vars',
124 )
125 await vi.advanceTimersByTimeAsync(10)
126β
127 const mutation = testCache.getAll()[0]
128β
129 expect(onSuccess).toHaveBeenCalledTimes(1)
130 expect(onSuccess).toHaveBeenCalledWith(
131 { data: 5 },
132 'vars',
133 'result',
134 mutation,
135 {
136 client: testClient,
137 meta: undefined,
138 mutationKey: key,
139 },
140 )
141 expect(onError).not.toHaveBeenCalled()
142 expect(onSettled).toHaveBeenCalledTimes(1)
143 expect(onSettled).toHaveBeenCalledWith(
144 { data: 5 },
145 null,
146 'vars',
147 'result',
148 mutation,
149 {
150 client: testClient,
151 meta: undefined,
152 mutationKey: key,
153 },
154 )
155 })
156β
157 it('should be awaited', async () => {
158 const key = queryKey()
159 const states: Array<number> = []
160 const onSuccess = () =>
161 sleep(10).then(() => {
162 states.push(1)
163 states.push(2)
164 })
165 const onSettled = () =>
166 sleep(10).then(() => {
167 states.push(5)
168 states.push(6)
169 })
170 const testCache = new MutationCache({ onSuccess, onSettled })
171 const testClient = new QueryClient({ mutationCache: testCache })
172β
173 executeMutation(
174 testClient,
175 {
176 mutationKey: key,
177 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
178 onSuccess: () =>
179 sleep(10).then(() => {
180 states.push(3)
181 states.push(4)
182 }),
183 onSettled: () =>
184 sleep(10).then(() => {
185 states.push(7)
186 states.push(8)
187 }),
188 },
189 'vars',
190 )
191 await vi.advanceTimersByTimeAsync(50)
192 expect(states).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
193 })
194 })
195β
196 describe('MutationCacheConfig.onMutate', () => {
197 it('should be called before a mutation executes', () => {
198 const key = queryKey()
199 const onMutate = vi.fn()
200 const testCache = new MutationCache({ onMutate })
201 const testClient = new QueryClient({ mutationCache: testCache })
202β
203 executeMutation(
204 testClient,
205 {
206 mutationKey: key,
207 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
208 onMutate: () => 'result',
209 },
210 'vars',
211 )
212β
213 const mutation = testCache.getAll()[0]
214β
215 expect(onMutate).toHaveBeenCalledWith('vars', mutation, {
216 client: testClient,
217 meta: undefined,
218 mutationKey: key,
219 })
220 })
221β
222 it('should be awaited', async () => {
223 const key = queryKey()
224 const states: Array<number> = []
225 const onMutate = () =>
226 sleep(10).then(() => {
227 states.push(1)
228 states.push(2)
229 })
230 const testCache = new MutationCache({ onMutate })
231 const testClient = new QueryClient({ mutationCache: testCache })
232β
233 executeMutation(
234 testClient,
235 {
236 mutationKey: key,
237 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
238 onMutate: () =>
239 sleep(10).then(() => {
240 states.push(3)
241 states.push(4)
242 }),
243 },
244 'vars',
245 )
246 await vi.advanceTimersByTimeAsync(20)
247 expect(states).toEqual([1, 2, 3, 4])
248 })
249β
250 it('should run options.onMutate synchronously when mutationCache.config.onMutate is not defined', () => {
251 const key = queryKey()
252 const states: Array<string> = []
253β
254 // No onMutate in cache config
255 const testCache = new MutationCache({})
256 const testClient = new QueryClient({ mutationCache: testCache })
257β
258 executeMutation(
259 testClient,
260 {
261 mutationKey: key,
262 mutationFn: () => sleep(10).then(() => ({ data: 5 })),
263 onMutate: () => {
264 states.push('onMutate')
265 return 'context'
266 },
267 },
268 'vars',
269 )
270 expect(states).toEqual(['onMutate'])
271 })
272 })
273β
274 describe('find', () => {
275 it('should filter correctly', () => {
276 const testCache = new MutationCache()
277 const testClient = new QueryClient({ mutationCache: testCache })
278 const key = ['mutation', 'vars']
279β
280 executeMutation(
281 testClient,
282 {
283 mutationKey: key,
284 mutationFn: () => sleep(10).then(() => undefined),
285 },
286 'vars',
287 )
288β
289 const [mutation] = testCache.getAll()
290β
291 expect(testCache.find({ mutationKey: key })).toEqual(mutation)
292 expect(
293 testCache.find({ mutationKey: ['mutation'], exact: false }),
294 ).toEqual(mutation)
295 expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined)
296 expect(
297 testCache.find({
298 predicate: (m) => m.options.mutationKey?.[0] === key[0],
299 }),
300 ).toEqual(mutation)
301 })
302 })
303β
304 describe('findAll', () => {
305 it('should filter correctly', () => {
306 const testCache = new MutationCache()
307 const testClient = new QueryClient({ mutationCache: testCache })
308β
309 executeMutation(
310 testClient,
311 {
312 mutationKey: ['a', 1],
313 mutationFn: () => sleep(10).then(() => undefined),
314 },
315 1,
316 )
317 executeMutation(
318 testClient,
319 {
320 mutationKey: ['a', 2],
321 mutationFn: () => sleep(10).then(() => undefined),
322 },
323 2,
324 )
325 executeMutation(
326 testClient,
327 {
328 mutationKey: ['b'],
329 mutationFn: () => sleep(10).then(() => undefined),
330 },
331 3,
332 )
333β
334 const [mutation1, mutation2] = testCache.getAll()
335β
336 expect(
337 testCache.findAll({ mutationKey: ['a'], exact: false }),
338 ).toHaveLength(2)
339 expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1)
340 expect(
341 testCache.findAll({
342 predicate: (m) => m.options.mutationKey?.[1] === 2,
343 }),
344 ).toEqual([mutation2])
345 expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([])
346 })
347 })
348β
349 describe('garbage collection', () => {
350 it('should remove unused mutations after gcTime has elapsed', async () => {
351 const testCache = new MutationCache()
352 const testClient = new QueryClient({ mutationCache: testCache })
353 const onSuccess = vi.fn()
354β
355 executeMutation(
356 testClient,
357 {
358 mutationKey: ['a', 1],
359 gcTime: 10,
360 mutationFn: () => sleep(10).then(() => undefined),
361 onSuccess,
362 },
363 1,
364 )
365 await vi.advanceTimersByTimeAsync(10)
366 expect(testCache.getAll()).toHaveLength(1)
367 await vi.advanceTimersByTimeAsync(10)
368 expect(testCache.getAll()).toHaveLength(0)
369 expect(onSuccess).toHaveBeenCalledTimes(1)
370 })
371β
372 it('should not remove mutations if there are active observers', async () => {
373 const queryClient = new QueryClient()
374 const observer = new MutationObserver(queryClient, {
375 gcTime: 10,
376 mutationFn: (input: number) => sleep(10).then(() => input),
377 })
378 const unsubscribe = observer.subscribe(() => undefined)
379 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
380β
381 observer.mutate(1)
382 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
383 await vi.advanceTimersByTimeAsync(10)
384 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
385β
386 unsubscribe()
387 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
388 await vi.advanceTimersByTimeAsync(10)
389 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
390 })
391β
392 it('should be garbage collected later when unsubscribed and mutation is pending', async () => {
393 const queryClient = new QueryClient()
394 const onSuccess = vi.fn()
395 const observer = new MutationObserver(queryClient, {
396 gcTime: 10,
397 mutationFn: () => sleep(10).then(() => 'data'),
398 onSuccess,
399 })
400 const unsubscribe = observer.subscribe(() => undefined)
401β
402 observer.mutate(1)
403β
404 unsubscribe()
405 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
406 await vi.advanceTimersByTimeAsync(10)
407 // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending
408 expect(queryClient.getMutationCache().getAll()).toHaveLength(1)
409 await vi.advanceTimersByTimeAsync(10)
410 // should be removed after an additional gcTime wait
411 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
412 expect(onSuccess).toHaveBeenCalledTimes(1)
413 })
414β
415 it('should call callbacks even with gcTime 0 and mutation still pending', async () => {
416 const queryClient = new QueryClient()
417 const onSuccess = vi.fn()
418 const observer = new MutationObserver(queryClient, {
419 gcTime: 0,
420 mutationFn: () => sleep(10).then(() => 'data'),
421 onSuccess,
422 })
423 const unsubscribe = observer.subscribe(() => undefined)
424β
425 observer.mutate(1)
426β
427 unsubscribe()
428 await vi.advanceTimersByTimeAsync(10)
429 expect(queryClient.getMutationCache().getAll()).toHaveLength(0)
430 expect(onSuccess).toHaveBeenCalledTimes(1)
431 })
432 })
433β
434 describe('remove', () => {
435 it('should remove only the target mutation from scope when multiple scoped mutations exist', () => {
436 const testCache = new MutationCache()
437 const testClient = new QueryClient({ mutationCache: testCache })
438β
439 const mutation1 = testCache.build(testClient, {
440 scope: { id: 'scope1' },
441 mutationFn: () => Promise.resolve('data1'),
442 })
443 const mutation2 = testCache.build(testClient, {
444 scope: { id: 'scope1' },
445 mutationFn: () => Promise.resolve('data2'),
446 })
447β
448 expect(testCache.getAll()).toHaveLength(2)
449β
450 testCache.remove(mutation1)
451β
452 expect(testCache.getAll()).toHaveLength(1)
453 expect(testCache.getAll()).toEqual([mutation2])
454 })
455β
456 it('should delete scope when removing the only mutation in that scope', () => {
457 const testCache = new MutationCache()
458 const testClient = new QueryClient({ mutationCache: testCache })
459β
460 const mutation = testCache.build(testClient, {
461 scope: { id: 'scope1' },
462 mutationFn: () => Promise.resolve('data'),
463 })
464β
465 expect(testCache.getAll()).toHaveLength(1)
466β
467 testCache.remove(mutation)
468β
469 expect(testCache.getAll()).toHaveLength(0)
470 })
471β
472 it('should still notify removal when removing a mutation that does not exist in the cache', () => {
473 const testCache = new MutationCache()
474 const testClient = new QueryClient({ mutationCache: testCache })
475β
476 const mutation = testCache.build(testClient, {
477 mutationFn: () => Promise.resolve('data'),
478 })
479β
480 expect(testCache.getAll()).toHaveLength(1)
481 testCache.remove(mutation)
482 expect(testCache.getAll()).toHaveLength(0)
483β
484 // Remove again β mutation is already gone from the cache
485 const callback = vi.fn()
486 const unsubscribe = testCache.subscribe(callback)
487 testCache.remove(mutation)
488β
489 expect(testCache.getAll()).toHaveLength(0)
490 expect(callback).toHaveBeenCalledTimes(1)
491 expect(callback).toHaveBeenCalledWith({ type: 'removed', mutation })
492β
493 unsubscribe()
494 })
495 })
496})