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

createQueriesController.test.ts

1,334 lines37.0 KB

1import { QueryClient } 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 { createQueriesController } from '../createQueriesController.js'
15import { queryOptions } from '../queryOptions.js'
16import { generateElementName } from './utils.js'
17import type { QueryObserverResult, QueryStatus } from '@tanstack/query-core'
18import type { QueriesResultAccessor } from '../createQueriesController.js'
19​
20const providerTagName = generateElementName()
21​
22describe('createQueriesController', () => {
23 let queryClient: QueryClient
24 let container: HTMLElement
25​
26 beforeAll(() => {
27 customElements.define(providerTagName, QueryClientProvider)
28 })
29​
30 beforeEach(() => {
31 vi.useFakeTimers()
32 queryClient = new QueryClient()
33 container = document.createElement('div')
34 document.body.append(container)
35 })
36​
37 afterEach(() => {
38 container.remove()
39 queryClient.clear()
40 vi.useRealTimers()
41 })
42​
43 it('should resolve from the pre-connect placeholder state on the first provider connection', async () => {
44 const key = createKey()
45​
46 class Consumer extends LitElement {
47 readonly queryKeys = [
48 [...key, 'alpha'],
49 [...key, 'beta'],
50 ]
51​
52 readonly queries = createQueriesController(this, {
53 queries: this.queryKeys.map((queryKey) => ({
54 queryKey,
55 queryFn: () => sleep(10).then(() => queryKey[1]),
56 retry: false,
57 })),
58 combine: (results) =>
59 results.map((result) => ({
60 status: result.status,
61 data: result.data,
62 })),
63 })
64​
65 override render() {
66 const results = this.queries()
67 .map((result) => `${result.status}:${result.data ?? 'none'}`)
68 .join(', ')
69 return html`results: ${results}`
70 }
71 }
72​
73 customElements.define(generateElementName(), Consumer)
74 const consumer = new Consumer()
75​
76 expect(consumer.queries()).toStrictEqual([
77 { status: 'pending', data: undefined },
78 { status: 'pending', data: undefined },
79 ])
80​
81 const provider = document.createElement(
82 providerTagName,
83 ) as QueryClientProvider
84 provider.client = queryClient
85 provider.append(consumer)
86 container.append(provider)
87 await provider.updateComplete
88 await consumer.updateComplete
89​
90 await vi.advanceTimersByTimeAsync(10)
91 expect(consumer.queries()[0]?.status).toBe('success')
92 expect(consumer.queries()[1]?.status).toBe('success')
93 expect(consumer.queries().map((item) => item.data)).toStrictEqual([
94 'alpha',
95 'beta',
96 ])
97 expect(consumer.shadowRoot).toHaveTextContent(
98 'results: success:alpha, success:beta',
99 )
100​
101 consumer.queries.destroy()
102 provider.remove()
103 })
104​
105 it('should prefer an explicit client over the provider context', async () => {
106 const key = createKey()
107 const providerClient = new QueryClient()
108​
109 const provider = document.createElement(
110 providerTagName,
111 ) as QueryClientProvider
112 provider.client = providerClient
113​
114 class Consumer extends LitElement {
115 readonly queryKeys = [
116 [...key, 'alpha'],
117 [...key, 'beta'],
118 ]
119​
120 readonly queries = createQueriesController(
121 this,
122 {
123 queries: this.queryKeys.map((queryKey) => ({
124 queryKey,
125 queryFn: () => sleep(10).then(() => queryKey[1]),
126 retry: false,
127 })),
128 combine: (results) =>
129 results.map((result) => ({
130 status: result.status,
131 data: result.data,
132 })),
133 },
134 queryClient,
135 )
136​
137 override render() {
138 const results = this.queries()
139 .map((result) => `${result.status}:${result.data ?? 'none'}`)
140 .join(', ')
141 return html`results: ${results}`
142 }
143 }
144​
145 customElements.define(generateElementName(), Consumer)
146 const consumer = new Consumer()
147 provider.append(consumer)
148 container.append(provider)
149 await provider.updateComplete
150 await consumer.updateComplete
151​
152 await vi.advanceTimersByTimeAsync(10)
153 expect(consumer.queries()[0]?.status).toBe('success')
154 expect(consumer.queries()[1]?.status).toBe('success')
155 expect(consumer.shadowRoot).toHaveTextContent(
156 'results: success:alpha, success:beta',
157 )
158 expect(
159 queryClient.getQueryCache().find({ queryKey: consumer.queryKeys[0]! })
160 ?.state.data,
161 ).toBe('alpha')
162 expect(
163 providerClient.getQueryCache().find({ queryKey: consumer.queryKeys[0]! }),
164 ).toBeUndefined()
165​
166 consumer.queries.destroy()
167 provider.remove()
168 })
169​
170 it('should combine multiple query results', async () => {
171 const key1 = createKey()
172 const key2 = createKey()
173​
174 class Host extends LitElement {
175 readonly queries = createQueriesController(
176 this,
177 {
178 queries: [
179 {
180 queryKey: key1,
181 queryFn: () => sleep(10).then(() => 'alpha'),
182 },
183 {
184 queryKey: key2,
185 queryFn: () => sleep(10).then(() => 'beta'),
186 },
187 ],
188 combine: (results) => results.map((result) => result.data),
189 },
190 queryClient,
191 )
192​
193 override render() {
194 const data = this.queries().map((result) => result ?? 'none')
195 return html`data: ${data.join(', ')}`
196 }
197 }
198​
199 customElements.define(generateElementName(), Host)
200 const host = new Host()
201 container.append(host)
202 const queries = host.queries
203 await host.updateComplete
204​
205 expect(host.shadowRoot).toHaveTextContent('data: none, none')
206 await vi.advanceTimersByTimeAsync(10)
207 expect(queries()).toStrictEqual(['alpha', 'beta'])
208 expect(host.shadowRoot).toHaveTextContent('data: alpha, beta')
209 })
210​
211 it('should not have stale closures with combine (#6648)', async () => {
212 const key = createKey()
213​
214 class Host extends LitElement {
215 static override properties = { count: { type: Number } }
216​
217 declare count: number
218​
219 readonly queries = createQueriesController(
220 this,
221 () => {
222 const { count } = this
223 return {
224 queries: [
225 {
226 queryKey: key,
227 queryFn: () => sleep(10).then(() => 'result'),
228 },
229 ],
230 combine: (results) => ({
231 count,
232 res: results.map((result) => result.data).join(','),
233 }),
234 }
235 },
236 queryClient,
237 )
238​
239 override render() {
240 const { count, res } = this.queries()
241 return html`data: ${String(count)} ${res}`
242 }
243 }
244​
245 customElements.define(generateElementName(), Host)
246 const host = new Host()
247​
248 host.count = 0
249 container.append(host)
250 await vi.advanceTimersByTimeAsync(10)
251 expect(host.shadowRoot).toHaveTextContent('data: 0 result')
252​
253 host.count = 1
254 await host.updateComplete
255​
256 expect(host.shadowRoot).toHaveTextContent('data: 1 result')
257 })
258​
259 it('should not request another update when stable function query options refresh during host update', async () => {
260 const key = createKey()
261 let callCount = 0
262​
263 class Host extends LitElement {
264 static override properties = { count: { type: Number } }
265​
266 declare count: number
267​
268 updatesRequested = 0
269​
270 readonly queries = createQueriesController(
271 this,
272 () => ({
273 queries: [
274 {
275 queryKey: key,
276 queryFn: () =>
277 sleep(10).then(() => {
278 callCount += 1
279 return 'stable-result'
280 }),
281 staleTime: Infinity,
282 },
283 ],
284 }),
285 queryClient,
286 )
287​
288 override requestUpdate(
289 ...args: Parameters<LitElement['requestUpdate']>
290 ): void {
291 this.updatesRequested += 1
292 super.requestUpdate(...args)
293 }
294 }
295​
296 customElements.define(generateElementName(), Host)
297 const host = new Host()
298 const queries = host.queries
299​
300 try {
301 container.append(host)
302 await vi.advanceTimersByTimeAsync(10)
303 expect(queries()[0].isSuccess).toBe(true)
304​
305 host.updatesRequested = 0
306​
307 for (let i = 0; i < 5; i += 1) {
308 host.count = i
309 await host.updateComplete
310 }
311 expect(host.updatesRequested).toBe(5)
312 expect(queries()[0].data).toBe('stable-result')
313 expect(callCount).toBe(1)
314 } finally {
315 queries.destroy()
316 }
317 })
318​
319 it('should not request an update for refetch-only state changes when data was read and result refetch is invoked', async () => {
320 const key = createKey()
321 let resolveRefetch: (() => void) | undefined
322​
323 class Host extends LitElement {
324 updatesRequested = 0
325​
326 readonly queries = createQueriesController(
327 this,
328 {
329 queries: [
330 {
331 queryKey: key,
332 initialData: 'stable-data',
333 staleTime: Infinity,
334 queryFn: () =>
335 new Promise<string>((resolve) => {
336 resolveRefetch = () => resolve('stable-data')
337 }),
338 },
339 ],
340 },
341 queryClient,
342 )
343​
344 override requestUpdate(
345 ...args: Parameters<LitElement['requestUpdate']>
346 ): void {
347 this.updatesRequested += 1
348 super.requestUpdate(...args)
349 }
350 }
351​
352 customElements.define(generateElementName(), Host)
353 const host = new Host()
354 const queries = host.queries
355​
356 try {
357 container.append(host)
358 await host.updateComplete
359 expect(queries()[0].data).toBe('stable-data')
360 await vi.advanceTimersByTimeAsync(0)
361​
362 host.updatesRequested = 0
363​
364 const refetch = queries()[0].refetch()
365​
366 expect(resolveRefetch).toBeDefined()
367 await vi.advanceTimersByTimeAsync(0)
368 expect(host.updatesRequested).toBe(0)
369​
370 resolveRefetch!()
371 await refetch
372 await vi.advanceTimersByTimeAsync(0)
373 expect(host.updatesRequested).toBe(0)
374 } finally {
375 queries.destroy()
376 }
377 })
378​
379 it('should not re-default query options when subscribed queries emit', async () => {
380 const originalDefaultQueryOptions = queryClient.defaultQueryOptions
381 let defaultQueryOptionsCalls = 0
382 queryClient.defaultQueryOptions = ((options) => {
383 defaultQueryOptionsCalls += 1
384 return originalDefaultQueryOptions.call(queryClient, options as never)
385 }) as typeof queryClient.defaultQueryOptions
386​
387 const key = createKey()
388 let resolveRefetch: (() => void) | undefined
389​
390 class Host extends LitElement {
391 readonly queries = createQueriesController(
392 this,
393 {
394 queries: [
395 {
396 queryKey: key,
397 initialData: 'stable-data',
398 staleTime: Infinity,
399 queryFn: () =>
400 new Promise<string>((resolve) => {
401 resolveRefetch = () => resolve('stable-data')
402 }),
403 },
404 ],
405 },
406 queryClient,
407 )
408 }
409​
410 customElements.define(generateElementName(), Host)
411 const host = new Host()
412 const queries = host.queries
413​
414 try {
415 container.append(host)
416 await host.updateComplete
417 expect(queries()[0].isFetching).toBe(false)
418 await vi.advanceTimersByTimeAsync(0)
419​
420 defaultQueryOptionsCalls = 0
421​
422 const refetch = queries()[0].refetch()
423​
424 expect(resolveRefetch).toBeDefined()
425 await vi.advanceTimersByTimeAsync(0)
426 expect(queries()[0].isFetching).toBe(true)
427 expect(defaultQueryOptionsCalls).toBe(0)
428​
429 resolveRefetch!()
430 await refetch
431 await vi.advanceTimersByTimeAsync(0)
432 expect(queries()[0].isFetching).toBe(false)
433 expect(defaultQueryOptionsCalls).toBe(0)
434 } finally {
435 queries.destroy()
436 }
437 })
438​
439 it('should refresh suppressed query results on the next accessor read when a newly read property changed', async () => {
440 const key = createKey()
441​
442 class Host extends LitElement {
443 updatesRequested = 0
444​
445 readonly queries = createQueriesController(
446 this,
447 {
448 queries: [
449 {
450 queryKey: key,
451 initialData: 'initial-data',
452 staleTime: Infinity,
453 queryFn: () => sleep(10).then(() => 'unused'),
454 },
455 ],
456 },
457 queryClient,
458 )
459​
460 override requestUpdate(
461 ...args: Parameters<LitElement['requestUpdate']>
462 ): void {
463 this.updatesRequested += 1
464 super.requestUpdate(...args)
465 }
466 }
467​
468 customElements.define(generateElementName(), Host)
469 const host = new Host()
470 const queries = host.queries
471​
472 try {
473 container.append(host)
474 await host.updateComplete
475 expect(queries()[0].status).toBe('success')
476 await vi.advanceTimersByTimeAsync(0)
477​
478 host.updatesRequested = 0
479​
480 queryClient.setQueryData(key, 'updated-data')
481 await vi.advanceTimersByTimeAsync(0)
482 expect(host.updatesRequested).toBe(0)
483​
484 expect(queries()[0].data).toBe('updated-data')
485 expect(host.updatesRequested).toBe(0)
486 } finally {
487 queries.destroy()
488 }
489 })
490​
491 it('should return the same result between reads when nothing changed', async () => {
492 const key = createKey()
493​
494 class Host extends LitElement {
495 readonly queries = createQueriesController(
496 this,
497 {
498 queries: [
499 {
500 queryKey: key,
501 queryFn: () => sleep(10).then(() => 'data'),
502 },
503 ],
504 },
505 queryClient,
506 )
507 }
508​
509 customElements.define(generateElementName(), Host)
510 const host = new Host()
511 container.append(host)
512 const queries = host.queries
513​
514 await vi.advanceTimersByTimeAsync(10)
515 const result = queries()
516 expect(queries()).toBe(result)
517 })
518​
519 it('should support dynamic add/remove and keep partial failure stability', async () => {
520 const key1 = createKey()
521 const key2 = createKey()
522 const key3 = createKey()
523 let includeThird = false
524 let includeFailing = true
525​
526 class Host extends LitElement {
527 readonly queries = createQueriesController(
528 this,
529 () => ({
530 queries: [
531 {
532 queryKey: key1,
533 queryFn: () => sleep(10).then(() => 'alpha'),
534 },
535 ...(includeFailing
536 ? [
537 {
538 queryKey: key2,
539 queryFn: () =>
540 sleep(10).then(() =>
541 Promise.reject(new Error('m13-fail')),
542 ),
543 retry: false,
544 },
545 ]
546 : []),
547 ...(includeThird
548 ? [
549 {
550 queryKey: key3,
551 queryFn: () => sleep(10).then(() => 'gamma'),
552 },
553 ]
554 : []),
555 ],
556 combine: (results) =>
557 results.map((result) => ({
558 status: result.status,
559 data: result.data,
560 error:
561 result.error instanceof Error ? result.error.message : null,
562 })),
563 }),
564 queryClient,
565 )
566​
567 override render() {
568 const results = this.queries()
569 .map(
570 (result) =>
571 `${result.status}:${result.data ?? result.error ?? 'none'}`,
572 )
573 .join(', ')
574 return html`results: ${results}`
575 }
576 }
577​
578 customElements.define(generateElementName(), Host)
579 const host = new Host()
580 container.append(host)
581 const queries = host.queries
582​
583 await vi.advanceTimersByTimeAsync(10)
584 expect(queries()).toHaveLength(2)
585 expect(queries()[0]).toMatchObject({ status: 'success', data: 'alpha' })
586 expect(queries()[1]).toMatchObject({ status: 'error', error: 'm13-fail' })
587 expect(host.shadowRoot).toHaveTextContent(
588 'results: success:alpha, error:m13-fail',
589 )
590​
591 includeThird = true
592 host.requestUpdate()
593 await vi.advanceTimersByTimeAsync(10)
594 expect(queries()).toHaveLength(3)
595 expect(queries()[0]?.status).toBe('success')
596 expect(queries()[1]?.status).toBe('error')
597 expect(queries()[2]).toMatchObject({ status: 'success', data: 'gamma' })
598 expect(host.shadowRoot).toHaveTextContent(
599 'results: success:alpha, error:m13-fail, success:gamma',
600 )
601​
602 includeFailing = false
603 host.requestUpdate()
604 await host.updateComplete
605 expect(queries()).toHaveLength(2)
606 expect(queries()[0]?.status).toBe('success')
607 expect(queries()[1]?.status).toBe('success')
608 expect(queries().map((item) => item.data)).toStrictEqual(['alpha', 'gamma'])
609 expect(host.shadowRoot).toHaveTextContent(
610 'results: success:alpha, success:gamma',
611 )
612 })
613​
614 it('should preserve the documented result order mapping when queries are reordered', async () => {
615 const key = createKey()
616 let order: Array<'first' | 'second'> = ['first', 'second']
617​
618 class Host extends LitElement {
619 readonly queries = createQueriesController(
620 this,
621 () => ({
622 queries: order.map((id) => ({
623 queryKey: [...key, id],
624 queryFn: () => sleep(10).then(() => id),
625 })),
626 combine: (results) => results.map((result) => result.data),
627 }),
628 queryClient,
629 )
630​
631 override render() {
632 const data = this.queries().map((result) => result ?? 'none')
633 return html`data: ${data.join(', ')}`
634 }
635 }
636​
637 customElements.define(generateElementName(), Host)
638 const host = new Host()
639 container.append(host)
640 const queries = host.queries
641​
642 await vi.advanceTimersByTimeAsync(10)
643 expect(queries()).toStrictEqual(['first', 'second'])
644 expect(host.shadowRoot).toHaveTextContent('data: first, second')
645​
646 order = ['second', 'first']
647 host.requestUpdate()
648 await host.updateComplete
649 expect(queries()).toStrictEqual(['second', 'first'])
650 expect(host.shadowRoot).toHaveTextContent('data: second, first')
651 })
652​
653 it('should return stable per-index results for duplicate query keys', async () => {
654 const key = createKey()
655 let callCount = 0
656​
657 class Host extends LitElement {
658 readonly queries = createQueriesController(
659 this,
660 {
661 queries: [
662 {
663 queryKey: key,
664 queryFn: () =>
665 sleep(10).then(() => {
666 callCount += 1
667 return 'shared-value'
668 }),
669 },
670 {
671 queryKey: key,
672 queryFn: () =>
673 sleep(10).then(() => {
674 callCount += 1
675 return 'shared-value'
676 }),
677 },
678 ],
679 combine: (results) =>
680 results.map((result) => ({
681 status: result.status,
682 data: result.data,
683 })),
684 },
685 queryClient,
686 )
687​
688 override render() {
689 const results = this.queries()
690 .map((result) => `${result.status}:${result.data ?? 'none'}`)
691 .join(', ')
692 return html`results: ${results}`
693 }
694 }
695​
696 customElements.define(generateElementName(), Host)
697 const host = new Host()
698 container.append(host)
699 const queries = host.queries
700​
701 await vi.advanceTimersByTimeAsync(10)
702 expect(queries()).toHaveLength(2)
703 expect(queries()[0]?.status).toBe('success')
704 expect(queries()[1]?.status).toBe('success')
705 expect(queries()[0]?.data).toBe('shared-value')
706 expect(queries()[1]?.data).toBe('shared-value')
707 expect(host.shadowRoot).toHaveTextContent(
708 'results: success:shared-value, success:shared-value',
709 )
710 expect(callCount).toBeGreaterThan(0)
711 })
712​
713 it('should not process detached updates when disconnected while in-flight', async () => {
714 const key = createKey()
715​
716 class Host extends LitElement {
717 updatesRequested = 0
718​
719 readonly queries = createQueriesController(
720 this,
721 {
722 queries: [
723 {
724 queryKey: key,
725 queryFn: () => sleep(10).then(() => 'data'),
726 },
727 ],
728 },
729 queryClient,
730 )
731​
732 override requestUpdate(
733 ...args: Parameters<LitElement['requestUpdate']>
734 ): void {
735 this.updatesRequested += 1
736 super.requestUpdate(...args)
737 }
738 }
739​
740 customElements.define(generateElementName(), Host)
741 const host = new Host()
742 container.append(host)
743 await host.updateComplete
744​
745 host.remove()
746 await host.updateComplete
747 const updatesAfterDisconnect = host.updatesRequested
748 await vi.advanceTimersByTimeAsync(10)
749 expect(host.updatesRequested).toBe(updatesAfterDisconnect)
750 })
751​
752 it('should fail after the handshake when the provider is missing and recover when a provider is adopted later', async () => {
753 const key = createKey()
754​
755 class Consumer extends LitElement {
756 readonly queryKeys = [
757 [...key, 'alpha'],
758 [...key, 'beta'],
759 ]
760​
761 readonly queries = createQueriesController(this, {
762 queries: this.queryKeys.map((queryKey) => ({
763 queryKey,
764 queryFn: () => sleep(10).then(() => queryKey[1]),
765 retry: false,
766 })),
767 combine: (results) =>
768 results.map((result) => ({
769 status: result.status,
770 data: result.data,
771 })),
772 })
773 }
774​
775 customElements.define(generateElementName(), Consumer)
776 const consumer = new Consumer()
777​
778 expect(consumer.queries()).toStrictEqual([
779 { status: 'pending', data: undefined },
780 { status: 'pending', data: undefined },
781 ])
782​
783 container.append(consumer)
784 expect(() => consumer.queries()).not.toThrow()
785 await vi.advanceTimersByTimeAsync(0)
786 expect(() => consumer.queries()).toThrow(/No QueryClient available/)
787​
788 const provider = document.createElement(
789 providerTagName,
790 ) as QueryClientProvider
791 provider.client = queryClient
792 provider.append(consumer)
793 container.append(provider)
794 await provider.updateComplete
795 await consumer.updateComplete
796​
797 await vi.advanceTimersByTimeAsync(10)
798 expect(consumer.queries()[0]?.status).toBe('success')
799 expect(consumer.queries()[1]?.status).toBe('success')
800 expect(consumer.queries().map((item) => item.data)).toStrictEqual([
801 'alpha',
802 'beta',
803 ])
804​
805 consumer.queries.destroy()
806 provider.remove()
807 })
808​
809 it('should reject placeholder refetch of raw query results after the missing-client handshake', async () => {
810 const key = createKey()
811​
812 class Consumer extends LitElement {
813 readonly queryKeys = [
814 [...key, 'alpha'],
815 [...key, 'beta'],
816 ]
817​
818 readonly queries = createQueriesController(this, {
819 queries: this.queryKeys.map((queryKey) => ({
820 queryKey,
821 queryFn: () => sleep(10).then(() => queryKey[1]),
822 retry: false,
823 })),
824 })
825 }
826​
827 customElements.define(generateElementName(), Consumer)
828 const consumer = new Consumer()
829​
830 const firstQuery = consumer.queries()[0]
831 expect(firstQuery?.status).toBe('pending')
832​
833 container.append(consumer)
834 await vi.advanceTimersByTimeAsync(0)
835 expect(() => consumer.queries()).toThrow(/No QueryClient available/)
836 await expect(firstQuery?.refetch()).rejects.toThrow(
837 'No QueryClient available. Pass one explicitly or render within QueryClientProvider.',
838 )
839​
840 consumer.queries.destroy()
841 consumer.remove()
842 })
843​
844 it('should defer placeholder accessors in the constructor until host fields are initialized', () => {
845 const key = createKey()
846​
847 class DeferredFieldsQueriesHost extends LitElement {
848 readonly queries = createQueriesController(this, () => ({
849 queries: this.ids.map((id) => ({
850 queryKey: [...key, id],
851 queryFn: () => sleep(10).then(() => id),
852 retry: false,
853 })),
854 combine: (results) => results.map((result) => result.status),
855 }))
856​
857 readonly firstRead = this.queries()
858 readonly ids = ['alpha', 'beta']
859 }
860​
861 customElements.define(generateElementName(), DeferredFieldsQueriesHost)
862​
863 expect(() => new DeferredFieldsQueriesHost()).not.toThrow()
864​
865 const host = new DeferredFieldsQueriesHost()
866 expect(host.queries()).toStrictEqual(['pending', 'pending'])
867 })
868​
869 it('should re-surface permanent placeholder combine errors after initialization', async () => {
870 const key = createKey()
871​
872 class Host extends LitElement {
873 readonly queries = createQueriesController(this, {
874 queries: [
875 {
876 queryKey: key,
877 queryFn: () => sleep(10).then(() => 'alpha'),
878 retry: false,
879 },
880 ],
881 combine: () => {
882 throw new Error('invalid combine')
883 },
884 })
885​
886 readonly firstRead = this.queries()
887 }
888​
889 customElements.define(generateElementName(), Host)
890​
891 expect(() => new Host()).not.toThrow()
892​
893 const host = new Host()
894 await vi.advanceTimersByTimeAsync(0)
895 expect(() => host.queries()).toThrow('invalid combine')
896 })
897​
898 it('should materialize defined initialData in placeholder combine before a client is available', () => {
899 const key = createKey()
900​
901 class Host extends LitElement {
902 readonly queries = createQueriesController(this, {
903 queries: [
904 queryOptions({
905 queryKey: key,
906 queryFn: () => sleep(10).then(() => ({ id: 4, name: 'Marie' })),
907 initialData: { id: 0, name: 'Seed' },
908 }),
909 ],
910 combine: (result) => result[0].data.name,
911 })
912 }
913​
914 customElements.define(generateElementName(), Host)
915 const host = new Host()
916 const queries = host.queries
917​
918 expect(queries()).toBe('Seed')
919​
920 queries.destroy()
921 })
922​
923 it('should call initialData and initialDataUpdatedAt functions in placeholder combine before a client is available', () => {
924 const key = createKey()
925​
926 class Host extends LitElement {
927 readonly queries = createQueriesController(this, {
928 queries: [
929 {
930 queryKey: key,
931 queryFn: () => sleep(10).then(() => 'fetched'),
932 initialData: () => 'seed',
933 initialDataUpdatedAt: () => 1000,
934 },
935 ],
936 combine: (result) => ({
937 data: result[0].data,
938 dataUpdatedAt: result[0].dataUpdatedAt,
939 }),
940 })
941 }
942​
943 customElements.define(generateElementName(), Host)
944 const host = new Host()
945 const queries = host.queries
946​
947 expect(queries()).toStrictEqual({ data: 'seed', dataUpdatedAt: 1000 })
948​
949 queries.destroy()
950 })
951​
952 it('should apply select to initialData in placeholder combine before a client is available', () => {
953 const key = createKey()
954​
955 class Host extends LitElement {
956 readonly queries = createQueriesController(this, {
957 queries: [
958 {
959 queryKey: key,
960 queryFn: () => sleep(10).then(() => 'fetched'),
961 initialData: 'seed',
962 select: (data: string) => data.toUpperCase(),
963 },
964 ],
965 combine: (result) => result[0].data,
966 })
967 }
968​
969 customElements.define(generateElementName(), Host)
970 const host = new Host()
971 const queries = host.queries
972​
973 expect(queries()).toBe('SEED')
974​
975 queries.destroy()
976 })
977​
978 it('should defer dynamic accessors in the explicit-client constructor until host fields are initialized', async () => {
979 const key = createKey()
980​
981 class DeferredExplicitQueriesHost extends LitElement {
982 readonly queries = createQueriesController(
983 this,
984 () => ({
985 queries: this.ids.map((id) => ({
986 queryKey: [...key, id],
987 queryFn: () => sleep(10).then(() => id),
988 retry: false,
989 })),
990 combine: (results) => results.map((result) => result.status),
991 }),
992 queryClient,
993 )
994​
995 readonly firstRead = this.queries()
996 readonly ids = ['alpha', 'beta']
997 }
998​
999 customElements.define(generateElementName(), DeferredExplicitQueriesHost)
1000​
1001 expect(() => new DeferredExplicitQueriesHost()).not.toThrow()
1002​
1003 const host = new DeferredExplicitQueriesHost()
1004 expect(host.queries()).toStrictEqual(['pending', 'pending'])
1005​
1006 container.append(host)
1007 await vi.advanceTimersByTimeAsync(10)
1008 expect(host.queries()).toStrictEqual(['success', 'success'])
1009​
1010 host.queries.destroy()
1011 })
1012​
1013 it('should defer static combine callbacks in the explicit-client constructor until host fields are initialized', async () => {
1014 const key = createKey()
1015​
1016 class DeferredExplicitCombineQueriesHost extends LitElement {
1017 readonly queries = createQueriesController(
1018 this,
1020 queries: [
1022 queryKey: key,
1023 queryFn: () => sleep(10).then(() => 'alpha'),
1024 retry: false,
1025 },
1026 ],
1027 combine: (results) =>
1028 this.ids.map((id, index) => `${id}:${results[index]?.status}`),
1029 },
1030 queryClient,
1032​
1033 readonly firstRead = this.queries()
1034 readonly ids = ['alpha']
1036​
1037 customElements.define(
1038 generateElementName(),
1039 DeferredExplicitCombineQueriesHost,
1041​
1042 expect(() => new DeferredExplicitCombineQueriesHost()).not.toThrow()
1043​
1044 const host = new DeferredExplicitCombineQueriesHost()
1045 expect(host.queries()).toStrictEqual(['alpha:pending'])
1046​
1047 container.append(host)
1048 await vi.advanceTimersByTimeAsync(10)
1049 expect(host.queries()).toStrictEqual(['alpha:success'])
1050​
1051 host.queries.destroy()
1052 })
1053​
1054 it('should re-surface permanent static combine errors in the explicit-client constructor after initialization', async () => {
1055 const key = createKey()
1056​
1057 class InvalidExplicitCombineQueriesHost extends LitElement {
1058 readonly queries = createQueriesController(
1059 this,
1061 queries: [
1063 queryKey: key,
1064 queryFn: () => sleep(10).then(() => 'alpha'),
1065 retry: false,
1066 },
1067 ],
1068 combine: () => {
1069 throw new Error('invalid combine')
1070 },
1071 },
1072 queryClient,
1075​
1076 customElements.define(
1077 generateElementName(),
1078 InvalidExplicitCombineQueriesHost,
1080​
1081 expect(() => new InvalidExplicitCombineQueriesHost()).not.toThrow()
1082​
1083 const host = new InvalidExplicitCombineQueriesHost()
1084 await vi.advanceTimersByTimeAsync(0)
1085 expect(() => host.queries()).toThrow('invalid combine')
1086 })
1087​
1088 it('should reuse hydrated data on an already-connected host without an eager refetch', async () => {
1089 const key = createKey()
1090 let queryFnCalls = 0
1091​
1092 queryClient.setQueryData(key, 'hydrated-value')
1093​
1094 class Host extends LitElement {
1095 queries?: QueriesResultAccessor<Array<QueryObserverResult<string>>>
1096​
1097 override render() {
1098 return html`data: ${this.queries?.()[0]?.data ?? 'none'}`
1101​
1102 customElements.define(generateElementName(), Host)
1103 const host = new Host()
1104 container.append(host)
1105 await host.updateComplete
1106​
1107 host.queries = createQueriesController(
1108 host,
1110 queries: [
1112 queryKey: key,
1113 queryFn: () => {
1114 queryFnCalls += 1
1115 return sleep(10).then(() => 'fetched-value')
1116 },
1117 staleTime: 30000,
1118 },
1119 ],
1120 },
1121 queryClient,
1123 const queries = host.queries
1124 await vi.advanceTimersByTimeAsync(0)
1125 expect(queries()[0]?.data).toBe('hydrated-value')
1126 expect(queryFnCalls).toBe(0)
1127 expect(host.shadowRoot).toHaveTextContent('data: hydrated-value')
1128​
1129 queries.destroy()
1130 })
1131​
1132 it('should not throw for a queries controller on an already-connected host with an explicit client', async () => {
1133 const key1 = createKey()
1134 const key2 = createKey()
1135 queryClient.setQueryData(key1, 'alpha')
1136 queryClient.setQueryData(key2, 'beta')
1137​
1138 class Host extends LitElement {
1139 queries?: QueriesResultAccessor<
1140 Array<{ status: QueryStatus; data: string | undefined }>
1143​
1144 customElements.define(generateElementName(), Host)
1145 const host = new Host()
1146 container.append(host)
1147 await host.updateComplete
1148​
1149 host.queries = createQueriesController(
1150 host,
1152 queries: [
1154 queryKey: key1,
1155 queryFn: () => sleep(10).then(() => 'fetched-alpha'),
1156 staleTime: 30000,
1157 },
1159 queryKey: key2,
1160 queryFn: () => sleep(10).then(() => 'fetched-beta'),
1161 staleTime: 30000,
1162 },
1163 ],
1164 combine: (results) =>
1165 results.map((result) => ({
1166 status: result.status,
1167 data: result.data,
1168 })),
1169 },
1170 queryClient,
1172 const queries = host.queries
1173 expect(queries()).toStrictEqual([
1174 { status: 'success', data: 'alpha' },
1175 { status: 'success', data: 'beta' },
1176 ])
1177 await vi.advanceTimersByTimeAsync(10)
1178 expect(queries()).toStrictEqual([
1179 { status: 'success', data: 'alpha' },
1180 { status: 'success', data: 'beta' },
1181 ])
1182​
1183 queries.destroy()
1184 })
1185​
1186 it('should switch queries controller to new provider client while connected', async () => {
1187 const key = createKey()
1188 const clientA = new QueryClient()
1189 const clientB = new QueryClient()
1190​
1191 const provider = document.createElement(
1192 providerTagName,
1193 ) as QueryClientProvider
1194 provider.client = clientA
1195 container.append(provider)
1196 await provider.updateComplete
1197​
1198 class Consumer extends LitElement {
1199 queryCalls = 0
1200 readonly queryKey = key
1201​
1202 readonly queries = createQueriesController(this, () => ({
1203 queries: [
1205 queryKey: this.queryKey,
1206 queryFn: () => {
1207 this.queryCalls += 1
1208 return sleep(10).then(() => `q-${this.queryCalls}`)
1209 },
1210 retry: false,
1211 },
1212 ],
1213 combine: (results) => results.map((result) => result.data),
1214 }))
1215​
1216 override render() {
1217 return html`data: ${this.queries()[0] ?? 'none'}`
1220​
1221 customElements.define(generateElementName(), Consumer)
1222 const consumer = new Consumer()
1223 provider.append(consumer)
1224​
1225 await vi.advanceTimersByTimeAsync(10)
1226 expect(consumer.queries()[0]).toBe('q-1')
1227 expect(consumer.shadowRoot).toHaveTextContent('data: q-1')
1228 const cacheAEntryBeforeSwitch = clientA
1229 .getQueryCache()
1230 .find({ queryKey: consumer.queryKey })
1231 expect(cacheAEntryBeforeSwitch?.getObserversCount()).toBe(1)
1232​
1233 provider.client = clientB
1234 await provider.updateComplete
1235​
1236 await vi.advanceTimersByTimeAsync(10)
1237 expect(
1238 clientB
1239 .getQueryCache()
1240 .find({ queryKey: consumer.queryKey })
1241 ?.getObserversCount(),
1242 ).toBe(1)
1243 expect(consumer.shadowRoot).toHaveTextContent('data: q-2')
1244 const cacheAEntryAfterSwitch = clientA
1245 .getQueryCache()
1246 .find({ queryKey: consumer.queryKey })
1247 expect(cacheAEntryAfterSwitch?.getObserversCount()).toBe(0)
1248​
1249 void clientB.invalidateQueries({ queryKey: consumer.queryKey })
1250 expect(consumer.queryCalls).toBe(3)
1251 await vi.advanceTimersByTimeAsync(10)
1252 expect(consumer.queries()[0]).toBe('q-3')
1253 expect(consumer.shadowRoot).toHaveTextContent('data: q-3')
1254​
1255 consumer.queries.destroy()
1256 provider.remove()
1257 })
1258​
1259 it('should reconnect queries controller under a different provider without cross-tree leakage', async () => {
1260 const key = createKey()
1261 const clientA = new QueryClient()
1262 const clientB = new QueryClient()
1263​
1264 const providerA = document.createElement(
1265 providerTagName,
1266 ) as QueryClientProvider
1267 providerA.client = clientA
1268 const providerB = document.createElement(
1269 providerTagName,
1270 ) as QueryClientProvider
1271 providerB.client = clientB
1272​
1273 class Consumer extends LitElement {
1274 queryCalls = 0
1275 readonly queryKey = key
1276​
1277 readonly queries = createQueriesController(this, () => ({
1278 queries: [
1280 queryKey: this.queryKey,
1281 queryFn: () => {
1282 this.queryCalls += 1
1283 return sleep(10).then(() => `q-${this.queryCalls}`)
1284 },
1285 retry: false,
1286 },
1287 ],
1288 combine: (results) => results.map((result) => result.data),
1289 }))
1291​
1292 customElements.define(generateElementName(), Consumer)
1293 const consumer = new Consumer()
1294 providerA.append(consumer)
1295 container.append(providerA)
1296 await providerA.updateComplete
1297​
1298 await vi.advanceTimersByTimeAsync(10)
1299 expect(consumer.queries()[0]).toBe('q-1')
1300​
1301 consumer.remove()
1302 expect(
1303 clientA
1304 .getQueryCache()
1305 .find({ queryKey: consumer.queryKey })
1306 ?.getObserversCount(),
1307 ).toBe(0)
1308​
1309 providerA.remove()
1310​
1311 providerB.append(consumer)
1312 container.append(providerB)
1313 await providerB.updateComplete
1314 await vi.advanceTimersByTimeAsync(10)
1315 expect(consumer.queries()[0]).toBe('q-2')
1316 expect(consumer.queryCalls).toBe(2)
1317 expect(
1318 clientA
1319 .getQueryCache()
1320 .find({ queryKey: consumer.queryKey })
1321 ?.getObserversCount(),
1322 ).toBe(0)
1323 expect(
1324 clientB
1325 .getQueryCache()
1326 .find({ queryKey: consumer.queryKey })
1327 ?.getObserversCount(),
1328 ).toBe(1)
1329​
1330 consumer.queries.destroy()
1331 providerA.remove()
1332 providerB.remove()
1333 })