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

mutationObserver.test.tsx

582 lines16.2 KB

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})