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

createMutationController.test.ts

1,054 lines31.1 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { QueryClient, noop } from '@tanstack/query-core'
3import { queryKey, sleep } from '@tanstack/query-test-utils'
4import { LitElement, html } from 'lit'
5import { QueryClientProvider } from '../QueryClientProvider.js'
6import { createMutationController } from '../createMutationController.js'
7import { generateElementName } from './utils.js'
8import type { MutationResultAccessor } from '../createMutationController.js'
9​
10const providerTagName = generateElementName()
11customElements.define(providerTagName, QueryClientProvider)
12​
13describe('createMutationController', () => {
14 let queryClient: QueryClient
15 let container: HTMLElement
16​
17 beforeEach(() => {
18 vi.useFakeTimers()
19 queryClient = new QueryClient()
20 container = document.createElement('div')
21 document.body.append(container)
22 })
23​
24 afterEach(() => {
25 container.remove()
26 queryClient.clear()
27 vi.useRealTimers()
28 })
29​
30 it('should resolve from the pre-connect placeholder state on the first provider connection', async () => {
31 const key = queryKey()
32​
33 class Consumer extends LitElement {
34 readonly mutationKey = key
35​
36 readonly mutation = createMutationController(this, {
37 mutationKey: this.mutationKey,
38 mutationFn: (value: number) => sleep(10).then(() => value + 1),
39 })
40​
41 override render() {
42 return html`status: ${this.mutation().status}`
43 }
44 }
45 customElements.define(generateElementName(), Consumer)
46 const consumer = new Consumer()
47​
48 expect(consumer.mutation().isIdle).toBe(true)
49 expect(() => consumer.mutation.mutate(1)).toThrow(
50 /No QueryClient available/,
51 )
52 await expect(consumer.mutation.mutateAsync(1)).rejects.toThrow(
53 /No QueryClient available/,
54 )
55​
56 const provider = document.createElement(
57 providerTagName,
58 ) as QueryClientProvider
59 provider.client = queryClient
60 provider.append(consumer)
61​
62 container.append(provider)
63 await provider.updateComplete
64 await consumer.updateComplete
65​
66 expect(consumer.shadowRoot).toHaveTextContent('status: idle')
67​
68 const mutatePromise = consumer.mutation.mutateAsync(1)
69 await vi.advanceTimersByTimeAsync(10)
70 await expect(mutatePromise).resolves.toBe(2)
71 expect(consumer.mutation().isSuccess).toBe(true)
72 expect(consumer.shadowRoot).toHaveTextContent('status: success')
73​
74 consumer.mutation.destroy()
75 provider.remove()
76 })
77​
78 it('should prefer an explicit client over the provider context', async () => {
79 const key = queryKey()
80 const providerClient = new QueryClient()
81​
82 const provider = document.createElement(
83 providerTagName,
84 ) as QueryClientProvider
85 provider.client = providerClient
86​
87 class Consumer extends LitElement {
88 readonly mutationKey = key
89​
90 readonly mutation = createMutationController(
91 this,
92 {
93 mutationKey: this.mutationKey,
94 mutationFn: (value: number) => sleep(10).then(() => value + 1),
95 },
96 queryClient,
97 )
98 }
99 customElements.define(generateElementName(), Consumer)
100 const consumer = new Consumer()
101 provider.append(consumer)
102​
103 container.append(provider)
104 await provider.updateComplete
105​
106 const mutatePromise = consumer.mutation.mutateAsync(2)
107 await vi.advanceTimersByTimeAsync(10)
108 await expect(mutatePromise).resolves.toBe(3)
109​
110 expect(
111 queryClient
112 .getMutationCache()
113 .findAll({ mutationKey: consumer.mutationKey }).length,
114 ).toBeGreaterThan(0)
115 expect(
116 providerClient
117 .getMutationCache()
118 .findAll({ mutationKey: consumer.mutationKey }).length,
119 ).toBe(0)
120​
121 consumer.mutation.destroy()
122 provider.remove()
123 })
124​
125 it('should resolve mutateAsync with the mutation data', async () => {
126 class Host extends LitElement {
127 readonly mutation = createMutationController(
128 this,
129 {
130 mutationFn: (value: number) => sleep(10).then(() => value + 1),
131 },
132 queryClient,
133 )
134​
135 override render() {
136 return html`data: ${this.mutation().data ?? 'none'}`
137 }
138 }
139 customElements.define(generateElementName(), Host)
140 const host = new Host()
141 container.append(host)
142 const mutation = host.mutation
143 await host.updateComplete
144​
145 expect(host.shadowRoot).toHaveTextContent('data: none')
146​
147 const resultPromise = mutation.mutateAsync(1)
148 await vi.advanceTimersByTimeAsync(10)
149 await expect(resultPromise).resolves.toBe(2)
150 expect(mutation().isSuccess).toBe(true)
151 expect(mutation().data).toBe(2)
152 expect(host.shadowRoot).toHaveTextContent('data: 2')
153 })
154​
155 it('should update the result when mutate succeeds', async () => {
156 class Host extends LitElement {
157 readonly mutation = createMutationController(
158 this,
159 {
160 mutationFn: (value: number) => sleep(10).then(() => value + 1),
161 },
162 queryClient,
163 )
164​
165 override render() {
166 return html`data: ${this.mutation().data ?? 'none'}`
167 }
168 }
169 customElements.define(generateElementName(), Host)
170 const host = new Host()
171 container.append(host)
172 const mutation = host.mutation
173 await host.updateComplete
174​
175 mutation.mutate(2)
176 await vi.advanceTimersByTimeAsync(10)
177 expect(mutation().data).toBe(3)
178 expect(mutation().isSuccess).toBe(true)
179 expect(host.shadowRoot).toHaveTextContent('data: 3')
180 })
181​
182 it('should be able to use mutation defaults', async () => {
183 const key = queryKey()
184​
185 queryClient.setMutationDefaults(key, {
186 mutationFn: (text: string) => sleep(10).then(() => text),
187 })
188​
189 class Host extends LitElement {
190 readonly mutation = createMutationController<string, unknown, string>(
191 this,
192 { mutationKey: key },
193 queryClient,
194 )
195​
196 override render() {
197 const { status, data } = this.mutation()
198 return html`status: ${status}, data: ${data ?? 'none'}`
199 }
200 }
201 customElements.define(generateElementName(), Host)
202 const host = new Host()
203 container.append(host)
204 await host.updateComplete
205​
206 expect(host.shadowRoot).toHaveTextContent('status: idle, data: none')
207​
208 host.mutation.mutate('todo')
209 await vi.advanceTimersByTimeAsync(0)
210 expect(host.shadowRoot).toHaveTextContent('status: pending, data: none')
211​
212 await vi.advanceTimersByTimeAsync(10)
213 expect(host.mutation().data).toBe('todo')
214 expect(host.shadowRoot).toHaveTextContent('status: success, data: todo')
215 })
216​
217 it('should transition from idle to pending to success', async () => {
218 class Host extends LitElement {
219 readonly mutation = createMutationController(
220 this,
221 {
222 mutationFn: (value: number) =>
223 sleep(10).then(() => {
224 if (value < 0) {
225 throw new Error('negative-not-allowed')
226 }
227 return value + 1
228 }),
229 },
230 queryClient,
231 )
232​
233 override render() {
234 const { status, data } = this.mutation()
235 return html`status: ${status}, data: ${data ?? 'none'}`
236 }
237 }
238 customElements.define(generateElementName(), Host)
239 const host = new Host()
240 container.append(host)
241 const mutation = host.mutation
242 await host.updateComplete
243​
244 expect(mutation().isIdle).toBe(true)
245 expect(host.shadowRoot).toHaveTextContent('status: idle, data: none')
246​
247 const successPromise = mutation.mutateAsync(10)
248 await vi.advanceTimersByTimeAsync(0)
249 expect(mutation().isPending).toBe(true)
250 expect(host.shadowRoot).toHaveTextContent('status: pending, data: none')
251 await vi.advanceTimersByTimeAsync(10)
252 await expect(successPromise).resolves.toBe(11)
253 expect(mutation().isSuccess).toBe(true)
254 expect(mutation().data).toBe(11)
255 expect(host.shadowRoot).toHaveTextContent('status: success, data: 11')
256 })
257​
258 it('should transition from pending to error when the mutation fails', async () => {
259 class Host extends LitElement {
260 readonly mutation = createMutationController(
261 this,
262 {
263 mutationFn: (value: number) =>
264 sleep(10).then(() => {
265 if (value < 0) {
266 throw new Error('negative-not-allowed')
267 }
268 return value + 1
269 }),
270 },
271 queryClient,
272 )
273​
274 override render() {
275 const { status, error } = this.mutation()
276 return html`status: ${status}, error: ${error?.message ?? 'none'}`
277 }
278 }
279 customElements.define(generateElementName(), Host)
280 const host = new Host()
281 container.append(host)
282 const mutation = host.mutation
283​
284 const errorPromise = mutation
285 .mutateAsync(-1)
286 .catch((error: unknown) => error)
287 await vi.advanceTimersByTimeAsync(0)
288 expect(mutation().isPending).toBe(true)
289 expect(host.shadowRoot).toHaveTextContent('status: pending, error: none')
290 await vi.advanceTimersByTimeAsync(10)
291 expect(await errorPromise).toEqual(new Error('negative-not-allowed'))
292 expect(mutation().isError).toBe(true)
293 expect(mutation().error).toEqual(new Error('negative-not-allowed'))
294 expect(host.shadowRoot).toHaveTextContent(
295 'status: error, error: negative-not-allowed',
296 )
297 })
298​
299 it('should reset mutation state back to the idle baseline', async () => {
300 class Host extends LitElement {
301 readonly mutation = createMutationController(
302 this,
303 {
304 mutationFn: () =>
305 sleep(10).then(() => Promise.reject(new Error('reset-target'))),
306 },
307 queryClient,
308 )
309​
310 override render() {
311 const { status, error } = this.mutation()
312 return html`status: ${status}, error: ${error?.message ?? 'none'}`
313 }
314 }
315 customElements.define(generateElementName(), Host)
316 const host = new Host()
317 container.append(host)
318 const mutation = host.mutation
319​
320 await Promise.all([
321 expect(mutation.mutateAsync(undefined)).rejects.toThrow('reset-target'),
322 vi.advanceTimersByTimeAsync(10),
323 ])
324 expect(mutation().isError).toBe(true)
325 expect(mutation().error).toEqual(new Error('reset-target'))
326 expect(host.shadowRoot).toHaveTextContent(
327 'status: error, error: reset-target',
328 )
329​
330 mutation.reset()
331 await vi.advanceTimersByTimeAsync(0)
332 expect(mutation().isIdle).toBe(true)
333 expect(mutation().isPaused).toBe(false)
334 expect(mutation().isError).toBe(false)
335 expect(mutation().error).toBeNull()
336 expect(mutation().data).toBeUndefined()
337 expect(host.shadowRoot).toHaveTextContent('status: idle, error: none')
338 })
339​
340 it('should call mutate callbacks when createMutationController has no callbacks', async () => {
341 const callbacks: Array<string> = []
342​
343 class Host extends LitElement {
344 readonly mutation = createMutationController(
345 this,
346 {
347 mutationFn: (text: string) => sleep(10).then(() => text),
348 },
349 queryClient,
350 )
351 }
352 customElements.define(generateElementName(), Host)
353 const host = new Host()
354 container.append(host)
355​
356 host.mutation.mutate('todo', {
357 onSuccess: () => {
358 callbacks.push('mutate.onSuccess')
359 },
360 onSettled: () => {
361 callbacks.push('mutate.onSettled')
362 },
363 })
364 await vi.advanceTimersByTimeAsync(10)
365 expect(callbacks).toEqual(['mutate.onSuccess', 'mutate.onSettled'])
366 })
367​
368 it('should call mutateAsync callbacks when createMutationController has no callbacks', async () => {
369 const callbacks: Array<string> = []
370​
371 class Host extends LitElement {
372 readonly mutation = createMutationController(
373 this,
374 {
375 mutationFn: (text: string) => sleep(10).then(() => text),
376 },
377 queryClient,
378 )
379 }
380 customElements.define(generateElementName(), Host)
381 const host = new Host()
382 container.append(host)
383​
384 host.mutation.mutateAsync('todo', {
385 onSuccess: () => {
386 callbacks.push('mutateAsync.onSuccess')
387 },
388 onSettled: () => {
389 callbacks.push('mutateAsync.onSettled')
390 },
391 })
392 await vi.advanceTimersByTimeAsync(10)
393 expect(callbacks).toEqual([
394 'mutateAsync.onSuccess',
395 'mutateAsync.onSettled',
396 ])
397 })
398​
399 it('should call mutate error callbacks when createMutationController has no callbacks', async () => {
400 const callbacks: Array<string> = []
401​
402 class Host extends LitElement {
403 readonly mutation = createMutationController(
404 this,
405 {
406 mutationFn: (_text: string) =>
407 sleep(10).then(() => {
408 throw new Error('oops')
409 }),
410 },
411 queryClient,
412 )
413 }
414 customElements.define(generateElementName(), Host)
415 const host = new Host()
416 container.append(host)
417​
418 host.mutation.mutate('todo', {
419 onError: () => {
420 callbacks.push('mutate.onError')
421 },
422 onSettled: () => {
423 callbacks.push('mutate.onSettled')
424 },
425 })
426 await vi.advanceTimersByTimeAsync(10)
427 expect(callbacks).toEqual(['mutate.onError', 'mutate.onSettled'])
428 })
429​
430 it('should call mutateAsync error callbacks when createMutationController has no callbacks', async () => {
431 const callbacks: Array<string> = []
432​
433 class Host extends LitElement {
434 readonly mutation = createMutationController(
435 this,
436 {
437 mutationFn: (_text: string) =>
438 sleep(10).then(() => {
439 throw new Error('oops')
440 }),
441 },
442 queryClient,
443 )
444 }
445 customElements.define(generateElementName(), Host)
446 const host = new Host()
447 container.append(host)
448​
449 host.mutation
450 .mutateAsync('todo', {
451 onError: () => {
452 callbacks.push('mutateAsync.onError')
453 },
454 onSettled: () => {
455 callbacks.push('mutateAsync.onSettled')
456 },
457 })
458 .catch(noop)
459 await vi.advanceTimersByTimeAsync(10)
460 expect(callbacks).toEqual(['mutateAsync.onError', 'mutateAsync.onSettled'])
461 })
462​
463 it('should call only mutate onSuccess when createMutationController has no callbacks', async () => {
464 const callbacks: Array<string> = []
465​
466 class Host extends LitElement {
467 readonly mutation = createMutationController(
468 this,
469 {
470 mutationFn: (text: string) => sleep(10).then(() => text),
471 },
472 queryClient,
473 )
474 }
475 customElements.define(generateElementName(), Host)
476 const host = new Host()
477 container.append(host)
478​
479 host.mutation.mutate('todo', {
480 onSuccess: () => {
481 callbacks.push('mutate.onSuccess')
482 },
483 })
484 await vi.advanceTimersByTimeAsync(10)
485 expect(callbacks).toEqual(['mutate.onSuccess'])
486 })
487​
488 it('should call only mutate onError when createMutationController has no callbacks', async () => {
489 const callbacks: Array<string> = []
490​
491 class Host extends LitElement {
492 readonly mutation = createMutationController(
493 this,
494 {
495 mutationFn: (_text: string) =>
496 sleep(10).then(() => {
497 throw new Error('oops')
498 }),
499 },
500 queryClient,
501 )
502 }
503 customElements.define(generateElementName(), Host)
504 const host = new Host()
505 container.append(host)
506​
507 host.mutation.mutate('todo', {
508 onError: () => {
509 callbacks.push('mutate.onError')
510 },
511 })
512 await vi.advanceTimersByTimeAsync(10)
513 expect(callbacks).toEqual(['mutate.onError'])
514 })
515​
516 it('should call only mutate onSettled when createMutationController has no callbacks', async () => {
517 const callbacks: Array<string> = []
518​
519 class Host extends LitElement {
520 readonly mutation = createMutationController(
521 this,
522 {
523 mutationFn: (text: string) => sleep(10).then(() => text),
524 },
525 queryClient,
526 )
527 }
528 customElements.define(generateElementName(), Host)
529 const host = new Host()
530 container.append(host)
531​
532 host.mutation.mutate('todo', {
533 onSettled: () => {
534 callbacks.push('mutate.onSettled')
535 },
536 })
537 await vi.advanceTimersByTimeAsync(10)
538 expect(callbacks).toEqual(['mutate.onSettled'])
539 })
540​
541 it('should call only mutateAsync onSuccess when createMutationController has no callbacks', async () => {
542 const callbacks: Array<string> = []
543​
544 class Host extends LitElement {
545 readonly mutation = createMutationController(
546 this,
547 {
548 mutationFn: (text: string) => sleep(10).then(() => text),
549 },
550 queryClient,
551 )
552 }
553 customElements.define(generateElementName(), Host)
554 const host = new Host()
555 container.append(host)
556​
557 host.mutation.mutateAsync('todo', {
558 onSuccess: () => {
559 callbacks.push('mutateAsync.onSuccess')
560 },
561 })
562 await vi.advanceTimersByTimeAsync(10)
563 expect(callbacks).toEqual(['mutateAsync.onSuccess'])
564 })
565​
566 it('should call only mutateAsync onError when createMutationController has no callbacks', async () => {
567 const callbacks: Array<string> = []
568​
569 class Host extends LitElement {
570 readonly mutation = createMutationController(
571 this,
572 {
573 mutationFn: (_text: string) =>
574 sleep(10).then(() => {
575 throw new Error('oops')
576 }),
577 },
578 queryClient,
579 )
580 }
581 customElements.define(generateElementName(), Host)
582 const host = new Host()
583 container.append(host)
584​
585 host.mutation
586 .mutateAsync('todo', {
587 onError: () => {
588 callbacks.push('mutateAsync.onError')
589 },
590 })
591 .catch(noop)
592 await vi.advanceTimersByTimeAsync(10)
593 expect(callbacks).toEqual(['mutateAsync.onError'])
594 })
595​
596 it('should call only mutateAsync onSettled when createMutationController has no callbacks', async () => {
597 const callbacks: Array<string> = []
598​
599 class Host extends LitElement {
600 readonly mutation = createMutationController(
601 this,
602 {
603 mutationFn: (text: string) => sleep(10).then(() => text),
604 },
605 queryClient,
606 )
607 }
608 customElements.define(generateElementName(), Host)
609 const host = new Host()
610 container.append(host)
611​
612 host.mutation.mutateAsync('todo', {
613 onSettled: () => {
614 callbacks.push('mutateAsync.onSettled')
615 },
616 })
617 await vi.advanceTimersByTimeAsync(10)
618 expect(callbacks).toEqual(['mutateAsync.onSettled'])
619 })
620​
621 it('should not throw from mutate while mutateAsync rejects on error', async () => {
622 class Host extends LitElement {
623 readonly mutation = createMutationController(
624 this,
625 {
626 mutationFn: (value: number) =>
627 sleep(10).then(() => {
628 if (value < 0) {
629 throw new Error('negative-not-allowed')
630 }
631​
632 return value + 1
633 }),
634 },
635 queryClient,
636 )
637 }
638 customElements.define(generateElementName(), Host)
639 const host = new Host()
640 container.append(host)
641 const mutation = host.mutation
642​
643 expect(() => mutation.mutate(-1)).not.toThrow()
644 await vi.advanceTimersByTimeAsync(10)
645 expect(mutation().isError).toBe(true)
646 expect(mutation().error).toEqual(new Error('negative-not-allowed'))
647​
648 await Promise.all([
649 expect(mutation.mutateAsync(-1)).rejects.toThrow('negative-not-allowed'),
650 vi.advanceTimersByTimeAsync(10),
651 ])
652 })
653​
654 it('should call mutation callbacks in a deterministic order and count', async () => {
655 const callbackEvents: Array<string> = []
656 class Host extends LitElement {
657 readonly mutation = createMutationController(
658 this,
659 {
660 mutationFn: (value: number) =>
661 sleep(10).then(() => {
662 if (value < 0) {
663 throw new Error('callback-order-failure')
664 }
665 return value + 1
666 }),
667 onSuccess: (_data, value) => {
668 callbackEvents.push(`success:${value}`)
669 },
670 onError: (_error, value) => {
671 callbackEvents.push(`error:${value}`)
672 },
673 onSettled: (_data, _error, value) => {
674 callbackEvents.push(`settled:${value}`)
675 },
676 },
677 queryClient,
678 )
679 }
680 customElements.define(generateElementName(), Host)
681 const host = new Host()
682 container.append(host)
683 const mutation = host.mutation
684​
685 const successPromise = mutation.mutateAsync(1)
686 await vi.advanceTimersByTimeAsync(10)
687 await expect(successPromise).resolves.toBe(2)
688​
689 await Promise.all([
690 expect(mutation.mutateAsync(-1)).rejects.toThrow(
691 'callback-order-failure',
692 ),
693 vi.advanceTimersByTimeAsync(10),
694 ])
695​
696 expect(callbackEvents).toEqual([
697 'success:1',
698 'settled:1',
699 'error:-1',
700 'settled:-1',
701 ])
702 })
703​
704 it('should use the latest closures for refreshed mutation callbacks', async () => {
705 const callbackEvents: Array<string> = []
706 let version = 'v1'
707 class Host extends LitElement {
708 readonly mutation = createMutationController(
709 this,
710 () => {
711 const callbackVersion = version
712​
713 return {
714 mutationFn: (value: number) =>
715 sleep(10).then(() => {
716 if (value < 0) {
717 throw new Error('freshness-failure')
718 }
719 return value + 1
720 }),
721 onSuccess: () => {
722 callbackEvents.push(`success:${callbackVersion}`)
723 },
724 onError: () => {
725 callbackEvents.push(`error:${callbackVersion}`)
726 },
727 onSettled: () => {
728 callbackEvents.push(`settled:${callbackVersion}`)
729 },
730 }
731 },
732 queryClient,
733 )
734 }
735 customElements.define(generateElementName(), Host)
736 const host = new Host()
737 container.append(host)
738 const mutation = host.mutation
739​
740 const successPromise = mutation.mutateAsync(1)
741 await vi.advanceTimersByTimeAsync(10)
742 await expect(successPromise).resolves.toBe(2)
743 expect(callbackEvents.slice(0, 2)).toEqual(['success:v1', 'settled:v1'])
744​
745 version = 'v2'
746 host.requestUpdate()
747 await host.updateComplete
748​
749 await Promise.all([
750 expect(mutation.mutateAsync(-1)).rejects.toThrow('freshness-failure'),
751 vi.advanceTimersByTimeAsync(10),
752 ])
753 expect(callbackEvents.slice(2)).toEqual(['error:v2', 'settled:v2'])
754 })
755​
756 it('should not process detached updates when disconnected while in-flight', async () => {
757 class Host extends LitElement {
758 updatesRequested = 0
759​
760 readonly mutation = createMutationController(
761 this,
762 {
763 mutationFn: (value: number) => sleep(10).then(() => value + 10),
764 },
765 queryClient,
766 )
767​
768 override requestUpdate(
769 ...args: Parameters<LitElement['requestUpdate']>
770 ): void {
771 this.updatesRequested += 1
772 super.requestUpdate(...args)
773 }
774 }
775 customElements.define(generateElementName(), Host)
776 const host = new Host()
777 const { mutation } = host
778​
779 container.append(host)
780 await host.updateComplete
781​
782 mutation.mutate(1)
783 host.remove()
784 await host.updateComplete
785 const updatesAfterDisconnect = host.updatesRequested
786​
787 await vi.advanceTimersByTimeAsync(10)
788 expect(host.updatesRequested).toBe(updatesAfterDisconnect)
789 })
790​
791 it('should become a deterministic missing-client state when the provider is missing', async () => {
792 const key = queryKey()
793​
794 class Consumer extends LitElement {
795 readonly mutationKey = key
796​
797 readonly mutation = createMutationController(this, {
798 mutationKey: this.mutationKey,
799 mutationFn: (value: number) => sleep(10).then(() => value + 1),
800 })
801 }
802 customElements.define(generateElementName(), Consumer)
803 const consumer = new Consumer()
804 const placeholderResult = consumer.mutation()
805​
806 expect(placeholderResult.isIdle).toBe(true)
807 expect(placeholderResult.isPaused).toBe(false)
808​
809 container.append(consumer)
810​
811 expect(() => consumer.mutation()).not.toThrow()
812 await vi.advanceTimersByTimeAsync(0)
813 expect(() => consumer.mutation()).toThrow(/No QueryClient available/)
814 expect(() => consumer.mutation.mutate(1)).toThrow(
815 /No QueryClient available/,
816 )
817 await expect(consumer.mutation.mutateAsync(1)).rejects.toThrow(
818 /No QueryClient available/,
819 )
820 await expect(placeholderResult.mutate(1)).rejects.toThrow(
821 /No QueryClient available/,
822 )
823​
824 expect(() => consumer.mutation.reset()).not.toThrow()
825 expect(() => placeholderResult.reset()).not.toThrow()
826​
827 consumer.mutation.destroy()
828 consumer.remove()
829 })
830​
831 it('should recover without reconstruction when a valid provider is adopted later', async () => {
832 const key = queryKey()
833​
834 class Consumer extends LitElement {
835 readonly mutationKey = key
836​
837 readonly mutation = createMutationController(this, {
838 mutationKey: this.mutationKey,
839 mutationFn: (value: number) => sleep(10).then(() => value + 1),
840 })
841 }
842 customElements.define(generateElementName(), Consumer)
843 const consumer = new Consumer()
844​
845 container.append(consumer)
846​
847 await vi.advanceTimersByTimeAsync(0)
848 expect(() => consumer.mutation()).toThrow(/No QueryClient available/)
849​
850 const provider = document.createElement(
851 providerTagName,
852 ) as QueryClientProvider
853 provider.client = queryClient
854 provider.append(consumer)
855​
856 container.append(provider)
857 await provider.updateComplete
858​
859 const mutatePromise = consumer.mutation.mutateAsync(1)
860 await vi.advanceTimersByTimeAsync(10)
861 await expect(mutatePromise).resolves.toBe(2)
862 expect(consumer.mutation().isSuccess).toBe(true)
863​
864 consumer.mutation.destroy()
865 provider.remove()
866 })
867​
868 it('should not throw for a mutation controller on an already-connected host with an explicit client', async () => {
869 // Regression test for SSR hydration scenario where controller is created
870 // during willUpdate on an already-connected host.
871 class Host extends LitElement {
872 mutation?: MutationResultAccessor<number, Error, number, unknown>
873 }
874 customElements.define(generateElementName(), Host)
875 const host = new Host()
876 container.append(host)
877 await host.updateComplete
878​
879 // Lit calls hostConnected immediately when a controller is added to an
880 // already-connected host
881 host.mutation = createMutationController(
882 host,
883 {
884 mutationKey: queryKey(),
885 mutationFn: (value: number) => sleep(10).then(() => value * 2),
886 },
887 queryClient,
888 )
889 const mutation = host.mutation
890​
891 // Wait for the deferred onConnected to complete
892 await vi.advanceTimersByTimeAsync(0)
893​
894 // Mutation controller should work correctly
895 expect(mutation().isIdle).toBe(true)
896​
897 const mutatePromise = mutation.mutateAsync(5)
898 await vi.advanceTimersByTimeAsync(10)
899 await expect(mutatePromise).resolves.toBe(10)
900 expect(mutation().isSuccess).toBe(true)
901​
902 mutation.destroy()
903 })
904​
905 it('should defer explicit-client mutation accessors until host fields are initialized', async () => {
906 const key = queryKey()
907​
908 class DeferredExplicitMutationHost extends LitElement {
909 readonly mutation = createMutationController(
910 this,
911 () => ({
912 mutationKey: [...key, this.id],
913 mutationFn: (value: number) =>
914 sleep(10).then(() => value + this.offset),
915 }),
916 queryClient,
917 )
918​
919 readonly firstRead = this.mutation()
920 readonly id = 'alpha'
921 readonly offset = 1
922 }
923 customElements.define(generateElementName(), DeferredExplicitMutationHost)
924​
925 expect(() => new DeferredExplicitMutationHost()).not.toThrow()
926​
927 const host = new DeferredExplicitMutationHost()
928 expect(host.mutation().isIdle).toBe(true)
929​
930 container.append(host)
931​
932 const mutatePromise = host.mutation.mutateAsync(1)
933 await vi.advanceTimersByTimeAsync(10)
934 await expect(mutatePromise).resolves.toBe(2)
935 expect(
936 queryClient
937 .getMutationCache()
938 .findAll({ mutationKey: key })
939 .map((mutation) => mutation.options.mutationKey),
940 ).toEqual([[...key, 'alpha']])
941​
942 host.mutation.destroy()
943 })
944​
945 it('should switch mutation controller to new provider client while connected', async () => {
946 const key = queryKey()
947 const clientA = new QueryClient()
948 const clientB = new QueryClient()
949​
950 const provider = document.createElement(
951 providerTagName,
952 ) as QueryClientProvider
953 provider.client = clientA
954 container.append(provider)
955 await provider.updateComplete
956​
957 class Consumer extends LitElement {
958 readonly mutationKey = key
959​
960 readonly mutation = createMutationController(this, () => ({
961 mutationKey: this.mutationKey,
962 mutationFn: (value: number) => sleep(10).then(() => value + 1),
963 }))
964 }
965 customElements.define(generateElementName(), Consumer)
966 const consumer = new Consumer()
967 provider.append(consumer)
968​
969 await vi.advanceTimersByTimeAsync(0)
970 const firstMutation = consumer.mutation.mutateAsync(1)
971 await vi.advanceTimersByTimeAsync(10)
972 await expect(firstMutation).resolves.toBe(2)
973​
974 const countAAfterFirst = clientA
975 .getMutationCache()
976 .findAll({ mutationKey: consumer.mutationKey }).length
977 expect(countAAfterFirst).toBeGreaterThan(0)
978​
979 provider.client = clientB
980 await provider.updateComplete
981 const secondMutation = consumer.mutation.mutateAsync(2)
982 await vi.advanceTimersByTimeAsync(10)
983 await expect(secondMutation).resolves.toBe(3)
984​
985 const countAAfterSecond = clientA
986 .getMutationCache()
987 .findAll({ mutationKey: consumer.mutationKey }).length
988 const countBAfterSecond = clientB
989 .getMutationCache()
990 .findAll({ mutationKey: consumer.mutationKey }).length
991​
992 expect(countAAfterSecond).toBe(countAAfterFirst)
993 expect(countBAfterSecond).toBeGreaterThan(0)
994​
995 consumer.mutation.destroy()
996 provider.remove()
997 })
998​
999 it('should reparent mutation controller under a different provider and bind the new nearest client', async () => {
1000 const key = queryKey()
1001 const clientA = new QueryClient()
1002 const clientB = new QueryClient()
1003​
1004 const providerA = document.createElement(
1005 providerTagName,
1006 ) as QueryClientProvider
1007 providerA.client = clientA
1008 const providerB = document.createElement(
1009 providerTagName,
1010 ) as QueryClientProvider
1011 providerB.client = clientB
1012​
1013 class Consumer extends LitElement {
1014 readonly mutationKey = key
1015​
1016 readonly mutation = createMutationController(this, () => ({
1017 mutationKey: this.mutationKey,
1018 mutationFn: (value: number) => sleep(10).then(() => value + 1),
1019 }))
1021 customElements.define(generateElementName(), Consumer)
1022 const consumer = new Consumer()
1023 providerA.append(consumer)
1024​
1025 container.append(providerA)
1026 await providerA.updateComplete
1027​
1028 const firstMutation = consumer.mutation.mutateAsync(1)
1029 await vi.advanceTimersByTimeAsync(10)
1030 await expect(firstMutation).resolves.toBe(2)
1031​
1032 consumer.remove()
1033 providerA.remove()
1034​
1035 providerB.append(consumer)
1036 container.append(providerB)
1037 await providerB.updateComplete
1038​
1039 const secondMutation = consumer.mutation.mutateAsync(2)
1040 await vi.advanceTimersByTimeAsync(10)
1041 await expect(secondMutation).resolves.toBe(3)
1042 expect(
1043 clientA.getMutationCache().findAll({ mutationKey: consumer.mutationKey })
1044 .length,
1045 ).toBeGreaterThan(0)
1046 expect(
1047 clientB.getMutationCache().findAll({ mutationKey: consumer.mutationKey })
1048 .length,
1049 ).toBeGreaterThan(0)
1050​
1051 consumer.mutation.destroy()
1052 providerB.remove()
1053 })