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

createQueriesController.test.ts

1,323 lines36.8 KB

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