Open History to see the last commit
1import { createKey, sleep } from '@tanstack/query-test-utils'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3import { MutationObserver, QueryClient } from '..'
4import type { MutationFunctionContext, MutationObserverResult } from '..'
5β
6describe('mutationObserver', () => {
7 let queryClient: QueryClient
8β
9 beforeEach(() => {
10 vi.useFakeTimers()
11 queryClient = new QueryClient()
12 queryClient.mount()
13 })
14β
15 afterEach(() => {
16 queryClient.clear()
17 vi.useRealTimers()
18 })
19β
20 it('should not remove the current mutation observer on onUnsubscribe if there is still a subscription', async () => {
21 const mutation = new MutationObserver(queryClient, {
22 mutationFn: (text: string) => sleep(20).then(() => text),
23 })
24β
25 const subscription1Handler =
26 vi.fn<
27 (result: MutationObserverResult<string, Error, string, unknown>) => void
28 >()
29 const subscription2Handler =
30 vi.fn<
31 (result: MutationObserverResult<string, Error, string, unknown>) => void
32 >()
33β
34 const unsubscribe1 = mutation.subscribe(subscription1Handler)
35 const unsubscribe2 = mutation.subscribe(subscription2Handler)
36β
37 mutation.mutate('input')
38β
39 unsubscribe1()
40 expect(subscription1Handler).toHaveBeenCalledTimes(1)
41 expect(subscription2Handler).toHaveBeenCalledTimes(1)
42 await vi.advanceTimersByTimeAsync(20)
43 expect(subscription1Handler).toHaveBeenCalledTimes(1)
44 expect(subscription2Handler).toHaveBeenCalledTimes(2)
45β
46 unsubscribe2()
47 })
48β
49 it('should remove observer on unsubscribe to trigger GC', async () => {
50 const mutation = new MutationObserver(queryClient, {
51 mutationFn: (text: string) => sleep(5).then(() => text),
52 gcTime: 10,
53 })
54β
55 const subscriptionHandler =
56 vi.fn<
57 (result: MutationObserverResult<string, Error, string, unknown>) => void
58 >()
59β
60 const unsubscribe = mutation.subscribe(subscriptionHandler)
61β
62 mutation.mutate('input')
63 await vi.advanceTimersByTimeAsync(5)
64 expect(queryClient.getMutationCache().findAll()).toHaveLength(1)
65β
66 unsubscribe()
67 await vi.advanceTimersByTimeAsync(10)
68 expect(queryClient.getMutationCache().findAll()).toHaveLength(0)
69 })
70β
71 it('should reattach the observer to the in-flight mutation when resubscribing', async () => {
72 const mutation = new MutationObserver(queryClient, {
73 mutationFn: (text: string) => sleep(20).then(() => text),
74 })
75β
76 const unsubscribe = mutation.subscribe(vi.fn())
77β
78 mutation.mutate('input')
79β
80 unsubscribe()
81β
82 const subscriptionHandler =
83 vi.fn<
84 (result: MutationObserverResult<string, Error, string, unknown>) => void
85 >()
86 mutation.subscribe(subscriptionHandler)
87 await vi.advanceTimersByTimeAsync(20)
88 expect(mutation.getCurrentResult()).toMatchObject({
89 status: 'success',
90 data: 'input',
91 })
92 expect(subscriptionHandler).toHaveBeenCalledTimes(1)
93 })
94β
95 it('should pick up a mutation that settled while unsubscribed when resubscribing', async () => {
96 const mutation = new MutationObserver(queryClient, {
97 mutationFn: (text: string) => sleep(20).then(() => text),
98 })
99β
100 const unsubscribe = mutation.subscribe(vi.fn())
101β
102 mutation.mutate('input')
103β
104 unsubscribe()
105 await vi.advanceTimersByTimeAsync(20)
106 mutation.subscribe(vi.fn())
107 expect(mutation.getCurrentResult()).toMatchObject({
108 status: 'success',
109 data: 'input',
110 })
111 })
112β
113 it('should remove observer on reset to trigger GC', async () => {
114 const mutation = new MutationObserver(queryClient, {
115 mutationFn: (text: string) => sleep(5).then(() => text),
116 gcTime: 10,
117 })
118β
119 const subscriptionHandler =
120 vi.fn<
121 (result: MutationObserverResult<string, Error, string, unknown>) => void
122 >()
123β
124 const unsubscribe = mutation.subscribe(subscriptionHandler)
125β
126 mutation.mutate('input')
127 await vi.advanceTimersByTimeAsync(5)
128 expect(queryClient.getMutationCache().findAll()).toHaveLength(1)
129β
130 mutation.reset()
131 await vi.advanceTimersByTimeAsync(10)
132 expect(queryClient.getMutationCache().findAll()).toHaveLength(0)
133β
134 unsubscribe()
135 })
136β
137 it('should reset the observer when changing mutation keys', async () => {
138 const key = createKey()
139 const mutation = new MutationObserver(queryClient, {
140 mutationKey: [...key, '1'],
141 mutationFn: (text: string) => sleep(5).then(() => text),
142 })
143β
144 const subscriptionHandler =
145 vi.fn<
146 (result: MutationObserverResult<string, Error, string, unknown>) => void
147 >()
148β
149 const unsubscribe = mutation.subscribe(subscriptionHandler)
150β
151 mutation.mutate('input')
152 await vi.advanceTimersByTimeAsync(5)
153 expect(mutation.getCurrentResult()).toMatchObject({
154 status: 'success',
155 data: 'input',
156 })
157β
158 mutation.setOptions({
159 mutationKey: [...key, '2'],
160 })
161 expect(mutation.getCurrentResult()).toMatchObject({
162 status: 'idle',
163 })
164β
165 unsubscribe()
166 })
167β
168 it('should not affect already existing mutations when changing mutation keys', async () => {
169 const key = createKey()
170 const mutationObserver = new MutationObserver(queryClient, {
171 mutationKey: [...key, '1'],
172 mutationFn: (text: string) => sleep(5).then(() => text),
173 })
174β
175 const subscriptionHandler =
176 vi.fn<
177 (result: MutationObserverResult<string, Error, string, unknown>) => void
178 >()
179β
180 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
181β
182 mutationObserver.mutate('input')
183 await vi.advanceTimersByTimeAsync(5)
184 expect(
185 queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }),
186 ).toMatchObject({
187 options: { mutationKey: [...key, '1'] },
188 state: {
189 status: 'success',
190 data: 'input',
191 },
192 })
193β
194 mutationObserver.setOptions({
195 mutationKey: [...key, '2'],
196 })
197 expect(
198 queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }),
199 ).toMatchObject({
200 options: { mutationKey: [...key, '1'] },
201 state: {
202 status: 'success',
203 data: 'input',
204 },
205 })
206β
207 unsubscribe()
208 })
209β
210 it('should not affect successful mutations when changing mutation meta', async () => {
211 const mutationObserver = new MutationObserver(queryClient, {
212 meta: { a: 1 },
213 mutationFn: (text: string) => sleep(5).then(() => text),
214 })
215β
216 const subscriptionHandler =
217 vi.fn<
218 (result: MutationObserverResult<string, Error, string, unknown>) => void
219 >()
220β
221 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
222β
223 mutationObserver.mutate('input')
224 await vi.advanceTimersByTimeAsync(5)
225 expect(queryClient.getMutationCache().find({})).toMatchObject({
226 options: { meta: { a: 1 } },
227 state: {
228 status: 'success',
229 data: 'input',
230 },
231 })
232β
233 mutationObserver.setOptions({
234 meta: { a: 2 },
235 })
236 expect(queryClient.getMutationCache().find({})).toMatchObject({
237 options: { meta: { a: 1 } },
238 state: {
239 status: 'success',
240 data: 'input',
241 },
242 })
243β
244 unsubscribe()
245 })
246β
247 it('should have different meta in mutation cache when updated between mutations', async () => {
248 const mutationFn = (text: string) => sleep(5).then(() => text)
249 const mutationObserver = new MutationObserver(queryClient, {
250 meta: { a: 1 },
251 mutationFn,
252 })
253β
254 const subscriptionHandler =
255 vi.fn<
256 (result: MutationObserverResult<string, Error, string, unknown>) => void
257 >()
258β
259 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
260β
261 mutationObserver.mutate('input')
262 await vi.advanceTimersByTimeAsync(5)
263β
264 mutationObserver.setOptions({
265 meta: { a: 2 },
266 mutationFn,
267 })
268β
269 mutationObserver.mutate('input')
270 await vi.advanceTimersByTimeAsync(5)
271β
272 const mutations = queryClient.getMutationCache().findAll()
273 expect(mutations[0]).toMatchObject({
274 options: { meta: { a: 1 } },
275 state: {
276 status: 'success',
277 data: 'input',
278 },
279 })
280 expect(mutations[1]).toMatchObject({
281 options: { meta: { a: 2 } },
282 state: {
283 status: 'success',
284 data: 'input',
285 },
286 })
287β
288 unsubscribe()
289 })
290β
291 it('should not affect rejected mutations when changing mutation meta', async () => {
292 const mutationObserver = new MutationObserver(queryClient, {
293 meta: { a: 1 },
294 mutationFn: (_: string) =>
295 sleep(5).then(() => Promise.reject(new Error('err'))),
296 })
297β
298 const subscriptionHandler =
299 vi.fn<
300 (result: MutationObserverResult<never, Error, string, unknown>) => void
301 >()
302β
303 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
304β
305 mutationObserver.mutate('input').catch(() => undefined)
306 await vi.advanceTimersByTimeAsync(5)
307 expect(queryClient.getMutationCache().find({})).toMatchObject({
308 options: { meta: { a: 1 } },
309 state: {
310 status: 'error',
311 },
312 })
313β
314 mutationObserver.setOptions({
315 meta: { a: 2 },
316 })
317 expect(queryClient.getMutationCache().find({})).toMatchObject({
318 options: { meta: { a: 1 } },
319 state: {
320 status: 'error',
321 },
322 })
323β
324 unsubscribe()
325 })
326β
327 it('should affect pending mutations when changing mutation meta', async () => {
328 const mutationObserver = new MutationObserver(queryClient, {
329 meta: { a: 1 },
330 mutationFn: (text: string) => sleep(20).then(() => text),
331 })
332β
333 const subscriptionHandler =
334 vi.fn<
335 (result: MutationObserverResult<string, Error, string, unknown>) => void
336 >()
337β
338 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
339β
340 mutationObserver.mutate('input')
341 await vi.advanceTimersByTimeAsync(5)
342 expect(queryClient.getMutationCache().find({})).toMatchObject({
343 options: { meta: { a: 1 } },
344 state: {
345 status: 'pending',
346 },
347 })
348β
349 mutationObserver.setOptions({
350 meta: { a: 2 },
351 })
352 expect(queryClient.getMutationCache().find({})).toMatchObject({
353 options: { meta: { a: 2 } },
354 state: {
355 status: 'pending',
356 },
357 })
358β
359 unsubscribe()
360 })
361β
362 it('should call mutation callbacks in correct order with correct arguments for success case', async () => {
363 const onSuccess =
364 vi.fn<
365 (
366 data: string,
367 variables: string,
368 onMutateResult: unknown,
369 context: MutationFunctionContext,
370 ) => void
371 >()
372 const onSettled =
373 vi.fn<
374 (
375 data: string | undefined,
376 error: Error | null,
377 variables: string,
378 onMutateResult: unknown,
379 context: MutationFunctionContext,
380 ) => void
381 >()
382β
383 const mutationObserver = new MutationObserver(queryClient, {
384 mutationFn: (text: string) => Promise.resolve(text.toUpperCase()),
385 })
386β
387 const subscriptionHandler =
388 vi.fn<
389 (result: MutationObserverResult<string, Error, string, unknown>) => void
390 >()
391 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
392β
393 mutationObserver.mutate('success', {
394 onSuccess,
395 onSettled,
396 })
397 await vi.advanceTimersByTimeAsync(0)
398 expect(onSuccess).toHaveBeenCalledTimes(1)
399 expect(onSuccess).toHaveBeenCalledWith('SUCCESS', 'success', undefined, {
400 client: queryClient,
401 meta: undefined,
402 mutationKey: undefined,
403 })
404 expect(onSettled).toHaveBeenCalledTimes(1)
405 expect(onSettled).toHaveBeenCalledWith(
406 'SUCCESS',
407 null,
408 'success',
409 undefined,
410 {
411 client: queryClient,
412 meta: undefined,
413 mutationKey: undefined,
414 },
415 )
416β
417 unsubscribe()
418 })
419β
420 it('should call mutation callbacks in correct order with correct arguments for error case', async () => {
421 const onError =
422 vi.fn<
423 (
424 error: Error,
425 variables: string,
426 onMutateResult: unknown,
427 context: MutationFunctionContext,
428 ) => void
429 >()
430 const onSettled =
431 vi.fn<
432 (
433 data: undefined,
434 error: Error | null,
435 variables: string,
436 onMutateResult: unknown,
437 context: MutationFunctionContext,
438 ) => void
439 >()
440β
441 const error = new Error('error')
442 const mutationObserver = new MutationObserver(queryClient, {
443 mutationFn: (_: string) => Promise.reject(error),
444 })
445β
446 const subscriptionHandler =
447 vi.fn<
448 (result: MutationObserverResult<never, Error, string, unknown>) => void
449 >()
450 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
451β
452 mutationObserver
453 .mutate('error', {
454 onError,
455 onSettled,
456 })
457 .catch(() => {})
458 await vi.advanceTimersByTimeAsync(0)
459 expect(onError).toHaveBeenCalledTimes(1)
460 expect(onError).toHaveBeenCalledWith(error, 'error', undefined, {
461 client: queryClient,
462 meta: undefined,
463 mutationKey: undefined,
464 })
465 expect(onSettled).toHaveBeenCalledTimes(1)
466 expect(onSettled).toHaveBeenCalledWith(
467 undefined,
468 error,
469 'error',
470 undefined,
471 {
472 client: queryClient,
473 meta: undefined,
474 mutationKey: undefined,
475 },
476 )
477β
478 unsubscribe()
479 })
480β
481 describe('erroneous mutation callback', () => {
482 it('should transfer onSuccess and onSettled to different execution context where they are reported', async ({
483 onTestFinished,
484 }) => {
485 const unhandledRejectionFn = vi.fn<NodeJS.UnhandledRejectionListener>()
486 process.on('unhandledRejection', unhandledRejectionFn)
487 onTestFinished(() => {
488 process.off('unhandledRejection', unhandledRejectionFn)
489 })
490β
491 const onSuccessError = new Error('onSuccess-error')
492 const onSuccess = vi.fn<() => never>(() => {
493 throw onSuccessError
494 })
495 const onSettledError = new Error('onSettled-error')
496 const onSettled = vi.fn<() => never>(() => {
497 throw onSettledError
498 })
499β
500 const mutationObserver = new MutationObserver(queryClient, {
501 mutationFn: (text: string) => Promise.resolve(text.toUpperCase()),
502 })
503β
504 const subscriptionHandler =
505 vi.fn<
506 (
507 result: MutationObserverResult<string, Error, string, unknown>,
508 ) => void
509 >()
510 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
511β
512 mutationObserver.mutate('success', {
513 onSuccess,
514 onSettled,
515 })
516 await vi.advanceTimersByTimeAsync(0)
517 expect(onSuccess).toHaveBeenCalledTimes(1)
518 expect(onSettled).toHaveBeenCalledTimes(1)
519β
520 expect(unhandledRejectionFn).toHaveBeenCalledTimes(2)
521 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
522 1,
523 onSuccessError,
524 expect.any(Promise),
525 )
526 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
527 2,
528 onSettledError,
529 expect.any(Promise),
530 )
531β
532 expect(subscriptionHandler).toHaveBeenCalledTimes(2)
533β
534 unsubscribe()
535 })
536β
537 it('should transfer onError and onSettled to different execution context where they are reported', async ({
538 onTestFinished,
539 }) => {
540 const unhandledRejectionFn = vi.fn<NodeJS.UnhandledRejectionListener>()
541 process.on('unhandledRejection', unhandledRejectionFn)
542 onTestFinished(() => {
543 process.off('unhandledRejection', unhandledRejectionFn)
544 })
545β
546 const onErrorError = new Error('onError-error')
547 const onError = vi.fn<() => never>(() => {
548 throw onErrorError
549 })
550 const onSettledError = new Error('onSettled-error')
551 const onSettled = vi.fn<() => never>(() => {
552 throw onSettledError
553 })
554β
555 const error = new Error('error')
556 const mutationObserver = new MutationObserver(queryClient, {
557 mutationFn: (_: string) => Promise.reject(error),
558 })
559β
560 const subscriptionHandler =
561 vi.fn<
562 (
563 result: MutationObserverResult<never, Error, string, unknown>,
564 ) => void
565 >()
566 const unsubscribe = mutationObserver.subscribe(subscriptionHandler)
567β
568 mutationObserver
569 .mutate('error', {
570 onError,
571 onSettled,
572 })
573 .catch(() => {})
574 await vi.advanceTimersByTimeAsync(0)
575 expect(onError).toHaveBeenCalledTimes(1)
576 expect(onSettled).toHaveBeenCalledTimes(1)
577β
578 expect(unhandledRejectionFn).toHaveBeenCalledTimes(2)
579 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
580 1,
581 onErrorError,
582 expect.any(Promise),
583 )
584 expect(unhandledRejectionFn).toHaveBeenNthCalledWith(
585 2,
586 onSettledError,
587 expect.any(Promise),
588 )
589β
590 expect(subscriptionHandler).toHaveBeenCalledTimes(2)
591β
592 unsubscribe()
593 })
594 })
595β
596 it('should not notify cache when setOptions is called with same options', () => {
597 const mutationObserver = new MutationObserver(queryClient, {
598 mutationFn: (text: string) => Promise.resolve(text),
599 })
600β
601 const notifySpy = vi.spyOn(queryClient.getMutationCache(), 'notify')
602β
603 const unsubscribe = mutationObserver.subscribe(() => undefined)
604β
605 notifySpy.mockClear()
606β
607 // Call setOptions with the same options
608 mutationObserver.setOptions({
609 mutationFn: mutationObserver.options.mutationFn,
610 })
611 expect(notifySpy).not.toHaveBeenCalledWith(
612 expect.objectContaining({ type: 'observerOptionsUpdated' }),
613 )
614β
615 unsubscribe()
616 })
617β
618 it('should not invoke onSettled with the next mutation options when mutate is called inside onSuccess', async () => {
619 // Regression test for https://github.com/TanStack/query/issues/11451
620 // If mutate() is called inside onSuccess, this.#mutateOptions is overwritten
621 // before onSettled fires. Without snapshotting mutateOptions at the start of
622 // #notify(), onSettled would receive the next mutation's callback but the
623 // current mutation's data/variables.
624 const onSettledFirst =
625 vi.fn<
626 (
627 data: number | undefined,
628 error: Error | null,
629 variables: number,
630 onMutateResult: unknown,
631 context: MutationFunctionContext,
632 ) => void
633 >()
634 const onSettledSecond =
635 vi.fn<
636 (
637 data: number | undefined,
638 error: Error | null,
639 variables: number,
640 onMutateResult: unknown,
641 context: MutationFunctionContext,
642 ) => void
643 >()
644β
645 const mutation = new MutationObserver(queryClient, {
646 mutationFn: (value: number) => Promise.resolve(value),
647 })
648β
649 const unsubscribe = mutation.subscribe(() => {})
650β
651 mutation.mutate(1, {
652 onSuccess: () => {
653 // Trigger a second mutation from inside onSuccess of the first
654 mutation.mutate(2, { onSettled: onSettledSecond })
655 },
656 onSettled: onSettledFirst,
657 })
658β
659 // Let both mutations settle
660 await vi.runAllTimersAsync()
661β
662 // onSettled for the first mutation must have been called with data=1
663 expect(onSettledFirst).toHaveBeenCalledTimes(1)
664 expect(onSettledFirst).toHaveBeenCalledWith(
665 1,
666 null,
667 1,
668 undefined,
669 expect.any(Object),
670 )
671β
672 // onSettled for the second mutation must have been called with data=2
673 expect(onSettledSecond).toHaveBeenCalledTimes(1)
674 expect(onSettledSecond).toHaveBeenCalledWith(
675 2,
676 null,
677 2,
678 undefined,
679 expect.any(Object),
680 )
681β
682 unsubscribe()
683 })
684β
685 it('should not invoke onSettled with the next mutation options when mutate is called inside onError', async () => {
686 const onSettledFirst =
687 vi.fn<
688 (
689 data: number | undefined,
690 error: Error | null,
691 variables: number,
692 onMutateResult: unknown,
693 context: MutationFunctionContext,
694 ) => void
695 >()
696 const onSettledSecond =
697 vi.fn<
698 (
699 data: number | undefined,
700 error: Error | null,
701 variables: number,
702 onMutateResult: unknown,
703 context: MutationFunctionContext,
704 ) => void
705 >()
706β
707 const error = new Error('error')
708 const mutation = new MutationObserver(queryClient, {
709 mutationFn: (value: number) =>
710 value === 1 ? Promise.reject(error) : Promise.resolve(value),
711 })
712β
713 const unsubscribe = mutation.subscribe(() => {})
714β
715 mutation
716 .mutate(1, {
717 onError: () => {
718 void mutation.mutate(2, { onSettled: onSettledSecond })
719 },
720 onSettled: onSettledFirst,
721 })
722 .catch(() => {})
723β
724 await vi.runAllTimersAsync()
725β
726 expect(onSettledFirst).toHaveBeenCalledTimes(1)
727 expect(onSettledFirst).toHaveBeenCalledWith(
728 undefined,
729 error,
730 1,
731 undefined,
732 expect.any(Object),
733 )
734β
735 expect(onSettledSecond).toHaveBeenCalledTimes(1)
736 expect(onSettledSecond).toHaveBeenCalledWith(
737 2,
738 null,
739 2,
740 undefined,
741 expect.any(Object),
742 )
743β
744 unsubscribe()
745 })
746})