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