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