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