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

inject-live-query.test.ts

1,237 lines34.0 KB

1import {
2 ApplicationRef,
3 ChangeDetectionStrategy,
4 Component,
5 DestroyRef,
6 inject,
7 input,
8 inputBinding,
9 signal,
10} from '@angular/core'
11import { TestBed } from '@angular/core/testing'
12import { render } from '@testing-library/angular'
13import { describe, expect, it } from 'vitest'
14import {
15 createCollection,
16 createLiveQueryCollection,
17 eq,
18 gt,
19} from '@tanstack/db'
20import { injectLiveQuery } from '../src/index'
21import { mockSyncCollectionOptions } from '../../db/tests/utils'
22import type {
23 Collection,
24 CollectionStatus,
25 Context,
26 LiveQueryCollectionConfig,
27 NonSingleResult,
28 QueryBuilder,
29} from '@tanstack/db'
30​
31// Import the same test utilities as Vue
32​
33type Person = {
34 id: string
35 name: string
36 age: number
37 email: string
38 isActive: boolean
39 team: string
41​
42const initialPersons: Array<Person> = [
43 {
44 id: `1`,
45 name: `John Doe`,
46 age: 30,
47 email: `john.doe@example.com`,
48 isActive: true,
49 team: `team1`,
50 },
51 {
52 id: `2`,
53 name: `Jane Doe`,
54 age: 25,
55 email: `jane.doe@example.com`,
56 isActive: true,
57 team: `team2`,
58 },
59 {
60 id: `3`,
61 name: `John Smith`,
62 age: 35,
63 email: `john.smith@example.com`,
64 isActive: true,
65 team: `team1`,
66 },
68​
69/** Waits until the app has no pending tasks (effects, CD, zone-patched timers). */
70async function waitForAngularUpdate() {
71 const appRef = TestBed.inject(ApplicationRef)
72 await appRef.whenStable()
74​
75function createMockCollection<T extends object, K extends string | number>(
76 initial: Array<T & Record<`id`, K>> = [],
77 initialStatus: CollectionStatus = `ready`,
78): Collection<T, K, Record<string, never>> &
79 NonSingleResult & {
80 __setStatus: (s: CollectionStatus) => void
81 __replaceAll: (rows: Array<T & Record<`id`, K>>) => void
82 __upsert: (row: T & Record<`id`, K>) => void
83 __delete: (key: K) => void
84 } {
85 const map = new Map<K, T>()
86 for (const r of initial) {
87 map.set(r.id, r)
88 }
89​
90 let status: CollectionStatus = initialStatus
91 const subs = new Set<(changes: Array<any>) => void>()
92 const readySubs = new Set<() => void>()
93 const id = `mock-col-` + Math.random().toString(36).slice(2)
94​
95 const notify = (changes: Array<any> = []) => {
96 for (const cb of subs) cb(changes)
97 }
98​
99 const notifyReady = () => {
100 for (const cb of readySubs) cb()
101 }
102​
103 const api: any = {
104 id,
105 get status() {
106 return status
107 },
108 entries: () => Array.from(map.entries()),
109 values: () => Array.from(map.values()),
110 get: (key: K) => map.get(key),
111 has: (key: K) => map.has(key),
112 size: () => map.size,
113 subscribeChanges: (cb: (changes: Array<any>) => void) => {
114 subs.add(cb)
115 return {
116 unsubscribe: () => subs.delete(cb),
117 }
118 },
119 onFirstReady: (cb: () => void) => {
120 if (status === `ready`) {
121 setTimeout(cb, 0)
122 } else {
123 readySubs.add(cb)
124 }
125 return () => readySubs.delete(cb)
126 },
127 preload: () => Promise.resolve(),
128 startSyncImmediate: () => {
129 const wasNotReady = status !== `ready`
130 if (status === `idle`) {
131 status = `ready`
132 }
133 if (wasNotReady && status === `ready`) {
134 setTimeout(notifyReady, 0)
135 }
136 },
137 __setStatus: (s: CollectionStatus) => {
138 const wasNotReady = status !== `ready`
139 status = s
140 notify([])
141 if (wasNotReady && status === `ready`) {
142 setTimeout(notifyReady, 0)
143 }
144 },
145 __replaceAll: (rows: Array<T & Record<`id`, K>>) => {
146 map.clear()
147 for (const r of rows) map.set(r.id, r)
148 notify([])
149 },
150 __upsert: (row: T & Record<`id`, K>) => {
151 const isUpdate = map.has(row.id)
152 map.set(row.id, row)
153 notify([
154 {
155 type: isUpdate ? `update` : `insert`,
156 key: row.id,
157 value: row,
158 },
159 ])
160 },
161 __delete: (key: K) => {
162 map.delete(key)
163 notify([
164 {
165 type: `delete`,
166 key: key,
167 },
168 ])
169 },
170 }
171​
172 return api
174​
175describe(`injectLiveQuery`, () => {
176 it(`throws if used outside injection context`, () => {
177 expect(() => {
178 injectLiveQuery(() => ({}) as unknown as QueryBuilder<Context>)
179 }).toThrow(
180 /NG0203:|injectLiveQuery\(\) can only be used within an injection context/i,
181 )
182 })
183​
184 it(`uses reactive params driven by a required signal input`, async () => {
185 const personsCollection = createCollection(
186 mockSyncCollectionOptions<Person>({
187 id: `test-persons-signal-input`,
188 getKey: (person: Person) => person.id,
189 initialData: initialPersons,
190 }),
191 )
192​
193 @Component({
194 template: `<span>{{ live.data().length }}</span>`,
195 standalone: true,
196 changeDetection: ChangeDetectionStrategy.OnPush,
197 })
198 class LiveQueryFromInputCmp {
199 minAge = input.required<number>()
200 live = injectLiveQuery({
201 params: () => ({ minAge: this.minAge() }),
202 query: ({ params, q }) =>
203 q
204 .from({ persons: personsCollection })
205 .where(({ persons }) => gt(persons.age, params.minAge))
206 .select(({ persons }) => ({
207 id: persons.id,
208 name: persons.name,
209 age: persons.age,
210 })),
211 })
212 }
213​
214 const minAge = signal(30)
215 const rendered = await render(LiveQueryFromInputCmp, {
216 bindings: [inputBinding(`minAge`, minAge.asReadonly())],
217 })
218​
219 expect(rendered.fixture.nativeElement.textContent).toContain(`1`)
220​
221 minAge.set(24)
222 rendered.fixture.detectChanges()
223 await waitForAngularUpdate()
224​
225 expect(rendered.fixture.nativeElement.textContent).toContain(`3`)
226 })
227​
228 it(`should work with basic collection and select`, async () => {
229 await TestBed.runInInjectionContext(async () => {
230 const collection = createCollection(
231 mockSyncCollectionOptions<Person>({
232 id: `test-persons-angular`,
233 getKey: (person: Person) => person.id,
234 initialData: initialPersons,
235 }),
236 )
237​
238 const { state, data } = injectLiveQuery((q) =>
239 q
240 .from({ persons: collection })
241 .where(({ persons }) => gt(persons.age, 30))
242 .select(({ persons }) => ({
243 id: persons.id,
244 name: persons.name,
245 age: persons.age,
246 })),
247 )
248​
249 await waitForAngularUpdate()
250​
251 expect(state().size).toBe(1) // Only John Smith (age 35)
252 expect(data()).toHaveLength(1)
253​
254 const johnSmith = data()[0]
255 expect(johnSmith).toMatchObject({
256 id: `3`,
257 name: `John Smith`,
258 age: 35,
259 })
260 })
261 })
262​
263 it(`initializes with an existing collection and exposes signals`, async () => {
264 await TestBed.runInInjectionContext(async () => {
265 const col = createMockCollection<{ id: number; name: string }, number>(
266 [{ id: 1, name: `A` }],
267 `ready`,
268 )
269​
270 const result = injectLiveQuery(col)
271​
272 await waitForAngularUpdate()
273​
274 expect(result.collection()).toBe(col)
275 expect(result.state().get(1)).toEqual({ id: 1, name: `A` })
276 expect(result.data()).toEqual([{ id: 1, name: `A` }])
277 expect(result.status()).toBe(`ready`)
278 expect(result.isReady()).toBe(true)
279 expect(result.isLoading()).toBe(false)
280 expect(result.isIdle()).toBe(false)
281 expect(result.isError()).toBe(false)
282 expect(result.isCleanedUp()).toBe(false)
283 })
284 })
285​
286 it(`subscribes to collection changes and updates signals`, async () => {
287 await TestBed.runInInjectionContext(async () => {
288 const col = createMockCollection<{ id: number; name: string }, number>(
289 [{ id: 1, name: `A` }],
290 `ready`,
291 )
292 const result = injectLiveQuery(col)
293​
294 await waitForAngularUpdate()
295​
296 col.__upsert({ id: 2, name: `B` })
297 await waitForAngularUpdate()
298​
299 expect(result.state().get(2)).toEqual({ id: 2, name: `B` })
300 expect(result.data()).toEqual([
301 { id: 1, name: `A` },
302 { id: 2, name: `B` },
303 ])
304​
305 col.__delete(1)
306 await waitForAngularUpdate()
307​
308 expect(result.state().has(1)).toBe(false)
309 expect(result.data()).toEqual([{ id: 2, name: `B` }])
310​
311 col.__replaceAll([{ id: 3, name: `C` }])
312 await waitForAngularUpdate()
313​
314 expect(Array.from(result.state().keys())).toEqual([3])
315 expect(result.data()).toEqual([{ id: 3, name: `C` }])
316 })
317 })
318​
319 it(`reflects status changes in derived flags`, async () => {
320 await TestBed.runInInjectionContext(async () => {
321 const col = createMockCollection<{ id: number; name: string }, number>(
322 [],
323 `idle`,
324 )
325 const { status, isReady, isLoading, isError, isCleanedUp } =
326 injectLiveQuery(col)
327​
328 await waitForAngularUpdate()
329​
330 expect(status()).toBe(`ready`) // Should be ready after startSyncImmediate
331 expect(isReady()).toBe(true)
332​
333 col.__setStatus(`loading`)
334 await waitForAngularUpdate()
335​
336 expect(status()).toBe(`loading`)
337 expect(isLoading()).toBe(true)
338​
339 col.__setStatus(`error`)
340 await waitForAngularUpdate()
341​
342 expect(status()).toBe(`error`)
343 expect(isError()).toBe(true)
344​
345 col.__setStatus(`cleaned-up`)
346 await waitForAngularUpdate()
347​
348 expect(status()).toBe(`cleaned-up`)
349 expect(isCleanedUp()).toBe(true)
350 })
351 })
352​
353 it(`should be able to query a collection with live updates`, async () => {
354 await TestBed.runInInjectionContext(async () => {
355 const collection = createCollection(
356 mockSyncCollectionOptions<Person>({
357 id: `test-persons-2-angular`,
358 getKey: (person: Person) => person.id,
359 initialData: initialPersons,
360 }),
361 )
362​
363 const { state, data } = injectLiveQuery((q) =>
364 q
365 .from({ collection })
366 .where(({ collection: c }) => gt(c.age, 30))
367 .select(({ collection: c }) => ({
368 id: c.id,
369 name: c.name,
370 }))
371 .orderBy(({ collection: c }) => c.id, `asc`),
372 )
373​
374 await waitForAngularUpdate()
375​
376 expect(state().size).toBe(1)
377 expect(state().get(`3`)).toMatchObject({
378 id: `3`,
379 name: `John Smith`,
380 })
381​
382 expect(data().length).toBe(1)
383 expect(data()[0]).toMatchObject({
384 id: `3`,
385 name: `John Smith`,
386 })
387​
388 // Insert a new person using the proper utils pattern
389 collection.utils.begin()
390 collection.utils.write({
391 type: `insert`,
392 value: {
393 id: `4`,
394 name: `Kyle Doe`,
395 age: 40,
396 email: `kyle.doe@example.com`,
397 isActive: true,
398 team: `team1`,
399 },
400 })
401 collection.utils.commit()
402​
403 await waitForAngularUpdate()
404​
405 expect(state().size).toBe(2)
406 expect(state().get(`3`)).toMatchObject({
407 id: `3`,
408 name: `John Smith`,
409 })
410 expect(state().get(`4`)).toMatchObject({
411 id: `4`,
412 name: `Kyle Doe`,
413 })
414​
415 expect(data().length).toBe(2)
416 expect(data()).toEqual(
417 expect.arrayContaining([
418 expect.objectContaining({
419 id: `3`,
420 name: `John Smith`,
421 }),
422 expect.objectContaining({
423 id: `4`,
424 name: `Kyle Doe`,
425 }),
426 ]),
427 )
428 })
429 })
430​
431 it.todo(
432 `reuses collection when deps are unchanged and query/config are same`,
433 async () => {
434 const collection = createCollection(
435 mockSyncCollectionOptions<Person>({
436 id: `reuse-test-angular`,
437 getKey: (person: Person) => person.id,
438 initialData: initialPersons,
439 }),
440 )
441​
442 const config: LiveQueryCollectionConfig<Context> = {
443 query: (q) =>
444 q
445 .from({ persons: collection })
446 .where(({ persons }) => gt(persons.age, 30))
447 .select(({ persons }) => ({
448 id: persons.id,
449 name: persons.name,
450 })),
451 startSync: true,
452 gcTime: 0,
453 }
454​
455 let col1: any
456 let col2: any
457​
458 await TestBed.runInInjectionContext(async () => {
459 const first = injectLiveQuery(config)
460 await waitForAngularUpdate()
461 col1 = first.collection()
462 })
463​
464 await TestBed.runInInjectionContext(async () => {
465 const second = injectLiveQuery(config)
466 await waitForAngularUpdate()
467 col2 = second.collection()
468 })
469​
470 expect(col2).toBe(col1)
471 },
472 )
473​
474 it(`creates a new collection when deps change`, async () => {
475 const collection = createCollection(
476 mockSyncCollectionOptions<Person>({
477 id: `deps-change-test-angular`,
478 getKey: (person: Person) => person.id,
479 initialData: initialPersons,
480 }),
481 )
482​
483 const config: LiveQueryCollectionConfig<Context> = {
484 query: (q) =>
485 q
486 .from({ persons: collection })
487 .where(({ persons }) => gt(persons.age, 30))
488 .select(({ persons }) => ({
489 id: persons.id,
490 name: persons.name,
491 })),
492 startSync: true,
493 gcTime: 0,
494 }
495​
496 let col1: any
497 let col2: any
498​
499 await TestBed.runInInjectionContext(async () => {
500 const first = injectLiveQuery(config)
501 await waitForAngularUpdate()
502 col1 = first.collection()
503 })
504​
505 await TestBed.runInInjectionContext(async () => {
506 const second = injectLiveQuery({
507 ...config,
508 gcTime: 1,
509 })
510 await waitForAngularUpdate()
511 col2 = second.collection()
512 })
513​
514 expect(col2).not.toBe(col1)
515 })
516​
517 it(`reuses exact same passed collection instance`, async () => {
518 await TestBed.runInInjectionContext(async () => {
519 const col = createMockCollection<{ id: number; name: string }, number>(
520 [],
521 `ready`,
522 )
523​
524 const a = injectLiveQuery(col)
525 const b = injectLiveQuery(col)
526​
527 await waitForAngularUpdate()
528​
529 expect(a.collection()).toBe(col)
530 expect(b.collection()).toBe(col)
531 })
532 })
533​
534 it(`cleans up subscription on destroy`, async () => {
535 await TestBed.runInInjectionContext(async () => {
536 const col = createMockCollection<{ id: number; name: string }, number>(
537 [{ id: 1, name: `A` }],
538 `ready`,
539 )
540​
541 const destroyRef = inject(DestroyRef)
542 const res = injectLiveQuery(col)
543​
544 await waitForAngularUpdate()
545​
546 col.__upsert({ id: 2, name: `B` })
547 await waitForAngularUpdate()
548​
549 expect(res.state().get(2)).toEqual({ id: 2, name: `B` })
550​
551 destroyRef.onDestroy(() => { })
552 })
553​
554 await TestBed.runInInjectionContext(async () => {
555 const col = createMockCollection<{ id: number; name: string }, number>(
556 [],
557 `ready`,
558 )
559 const res = injectLiveQuery(col)
560​
561 await waitForAngularUpdate()
562​
563 expect(res.data()).toEqual([])
564 })
565 })
566​
567 it(`accepts a query function and initializes collection via createLiveQueryCollection`, async () => {
568 await TestBed.runInInjectionContext(async () => {
569 const collection = createCollection(
570 mockSyncCollectionOptions<Person>({
571 id: `query-fn-test-angular`,
572 getKey: (person: Person) => person.id,
573 initialData: initialPersons,
574 }),
575 )
576​
577 const res = injectLiveQuery((q) =>
578 q
579 .from({ persons: collection })
580 .where(({ persons }) => gt(persons.age, 30))
581 .select(({ persons }) => ({
582 id: persons.id,
583 name: persons.name,
584 })),
585 )
586​
587 await waitForAngularUpdate()
588​
589 expect(res.collection()!.id).toEqual(expect.any(String))
590 expect(res.status()).toBe(`ready`)
591 expect(Array.isArray(res.data())).toBe(true)
592 expect(res.state() instanceof Map).toBe(true)
593 })
594 })
595​
596 it(`accepts a LiveQueryCollectionConfig object`, async () => {
597 await TestBed.runInInjectionContext(async () => {
598 const collection = createCollection(
599 mockSyncCollectionOptions<Person>({
600 id: `config-test-angular`,
601 getKey: (person: Person) => person.id,
602 initialData: initialPersons,
603 }),
604 )
605​
606 const config: LiveQueryCollectionConfig<Context> = {
607 query: (q) =>
608 q
609 .from({ persons: collection })
610 .where(({ persons }) => gt(persons.age, 30))
611 .select(({ persons }) => ({
612 id: persons.id,
613 name: persons.name,
614 })),
615 startSync: true,
616 gcTime: 0,
617 }
618​
619 const res = injectLiveQuery(config)
620 await waitForAngularUpdate()
621​
622 expect(res.collection()!.id).toEqual(expect.any(String))
623 expect(res.isReady()).toBe(true)
624 })
625 })
626​
627 it(`throws from computed collection if not initialized (defensive path)`, async () => {
628 await TestBed.runInInjectionContext(async () => {
629 const col = createMockCollection<{ id: number; name: string }, number>(
630 [],
631 `ready`,
632 )
633 const res = injectLiveQuery(col)
634​
635 await waitForAngularUpdate()
636​
637 expect(res.collection()).toBe(col)
638 })
639 })
640​
641 it(`accepts reactive params with query function`, async () => {
642 await TestBed.runInInjectionContext(async () => {
643 const collection = createCollection(
644 mockSyncCollectionOptions<Person>({
645 id: `reactive-params-test-angular`,
646 getKey: (person: Person) => person.id,
647 initialData: initialPersons,
648 }),
649 )
650​
651 const projectId = signal(1)
652​
653 const res = injectLiveQuery({
654 params: () => ({ projectID: projectId() }),
655 query: ({ params, q }) =>
656 q
657 .from({ persons: collection })
658 .where(({ persons }) => eq(persons.team, `team${params.projectID}`))
659 .select(({ persons }) => ({
660 id: persons.id,
661 name: persons.name,
662 team: persons.team,
663 })),
664 })
665​
666 await waitForAngularUpdate()
667​
668 expect(res.collection()!.id).toEqual(expect.any(String))
669 expect(res.status()).toBe(`ready`)
670 expect(Array.isArray(res.data())).toBe(true)
671 expect(res.state() instanceof Map).toBe(true)
672​
673 // Should get team1 people (John Doe and John Smith) when projectID is 1
674 expect(res.data()).toHaveLength(2)
675 expect(res.data()).toEqual(
676 expect.arrayContaining([
677 expect.objectContaining({
678 id: `1`,
679 name: `John Doe`,
680 team: `team1`,
681 }),
682 expect.objectContaining({
683 id: `3`,
684 name: `John Smith`,
685 team: `team1`,
686 }),
687 ]),
688 )
689​
690 projectId.set(2)
691 await waitForAngularUpdate()
692​
693 // Should get team2 person (Jane Doe) when projectID is 2
694 expect(res.data()).toHaveLength(1)
695 expect(res.data()[0]).toMatchObject({
696 id: `2`,
697 name: `Jane Doe`,
698 team: `team2`,
699 })
700 })
701 })
702​
703 it(`reactive params update when signal changes`, async () => {
704 await TestBed.runInInjectionContext(async () => {
705 const collection = createCollection(
706 mockSyncCollectionOptions<Person>({
707 id: `reactive-update-test-angular`,
708 getKey: (person: Person) => person.id,
709 initialData: initialPersons,
710 }),
711 )
712​
713 const selectedProjectId = signal(2)
714​
715 const res = injectLiveQuery({
716 params: () => ({ projectID: selectedProjectId() }),
717 query: ({ params, q }) =>
718 q
719 .from({ persons: collection })
720 .where(({ persons }) => eq(persons.team, `team${params.projectID}`))
721 .select(({ persons }) => ({
722 id: persons.id,
723 name: persons.name,
724 team: persons.team,
725 })),
726 })
727​
728 await waitForAngularUpdate()
729​
730 expect(res.isReady()).toBe(true)
731 // Should initially show team2 data
732 expect(res.data()).toHaveLength(1)
733 expect(res.data()[0]).toMatchObject({
734 id: `2`,
735 name: `Jane Doe`,
736 team: `team2`,
737 })
738​
739 selectedProjectId.set(1)
740 await waitForAngularUpdate()
741​
742 expect(selectedProjectId()).toBe(1)
743 // Should now show team1 data (2 people)
744 expect(res.data()).toHaveLength(2)
745 expect(res.data()).toEqual(
746 expect.arrayContaining([
747 expect.objectContaining({
748 id: `1`,
749 name: `John Doe`,
750 team: `team1`,
751 }),
752 expect.objectContaining({
753 id: `3`,
754 name: `John Smith`,
755 team: `team1`,
756 }),
757 ]),
758 )
759 })
760 })
761​
762 it(`should accept pre-created live query collection`, async () => {
763 await TestBed.runInInjectionContext(async () => {
764 const collection = createCollection(
765 mockSyncCollectionOptions<Person>({
766 id: `pre-created-collection-test-angular`,
767 getKey: (person: Person) => person.id,
768 initialData: initialPersons,
769 }),
770 )
771​
772 // Create a live query collection beforehand
773 const liveQueryCollection = createLiveQueryCollection({
774 query: (q) =>
775 q
776 .from({ persons: collection })
777 .where(({ persons }) => gt(persons.age, 30))
778 .select(({ persons }) => ({
779 id: persons.id,
780 name: persons.name,
781 age: persons.age,
782 })),
783 startSync: true,
784 })
785​
786 const {
787 state,
788 data,
789 collection: returnedCollection,
790 } = injectLiveQuery(liveQueryCollection)
791​
792 await waitForAngularUpdate()
793​
794 expect(state().size).toBe(1) // Only John Smith (age 35)
795 expect(data()).toHaveLength(1)
796​
797 const johnSmith = data()[0]
798 expect(johnSmith).toMatchObject({
799 id: `3`,
800 name: `John Smith`,
801 age: 35,
802 })
803​
804 // Verify that the returned collection is the same instance
805 expect(returnedCollection()).toBe(liveQueryCollection)
806 })
807 })
808​
809 it(`should return a single object for findOne query`, async () => {
810 await TestBed.runInInjectionContext(async () => {
811 const collection = createCollection(
812 mockSyncCollectionOptions<Person>({
813 id: `test-persons-findone-angular`,
814 getKey: (person: Person) => person.id,
815 initialData: initialPersons,
816 }),
817 )
818​
819 const { state, data } = injectLiveQuery((q) =>
820 q
821 .from({ collection })
822 .where(({ collection: c }) => eq(c.id, `3`))
823 .findOne(),
824 )
825​
826 await waitForAngularUpdate()
827​
828 expect(state().size).toBe(1)
829 expect(state().get(`3`)).toMatchObject({
830 id: `3`,
831 name: `John Smith`,
832 })
833​
834 // findOne should return a single object, not an array
835 expect(Array.isArray(data())).toBe(false)
836 expect(data()).toMatchObject({
837 id: `3`,
838 name: `John Smith`,
839 })
840 })
841 })
842​
843 describe(`eager execution during sync`, () => {
844 it(`should show state while isLoading is true during sync`, async () => {
845 await TestBed.runInInjectionContext(async () => {
846 let syncBegin: (() => void) | undefined
847 let syncWrite: ((op: any) => void) | undefined
848 let syncCommit: (() => void) | undefined
849 let syncMarkReady: (() => void) | undefined
850​
851 const collection = createCollection<Person>({
852 id: `eager-execution-test-angular`,
853 getKey: (person: Person) => person.id,
854 startSync: false,
855 sync: {
856 sync: ({ begin, write, commit, markReady }) => {
857 syncBegin = begin
858 syncWrite = write
859 syncCommit = commit
860 syncMarkReady = markReady
861 },
862 },
863 onInsert: () => Promise.resolve(),
864 onUpdate: () => Promise.resolve(),
865 onDelete: () => Promise.resolve(),
866 })
867​
868 const {
869 isLoading,
870 state,
871 data,
872 collection: liveQueryCollection,
873 } = injectLiveQuery({
874 query: (q) =>
875 q
876 .from({ persons: collection })
877 .where(({ persons }) => gt(persons.age, 30))
878 .select(({ persons }) => ({
879 id: persons.id,
880 name: persons.name,
881 })),
882 startSync: false,
883 })
884​
885 // Start the live query sync manually
886 liveQueryCollection()!.preload()
887​
888 await waitForAngularUpdate()
889​
890 // Now isLoading should be true
891 expect(isLoading()).toBe(true)
892 expect(state().size).toBe(0)
893 expect(data()).toEqual([])
894​
895 // Add first batch of data (but don't mark ready yet)
896 syncBegin!()
897 syncWrite!({
898 type: `insert`,
899 value: {
900 id: `1`,
901 name: `John Smith`,
902 age: 35,
903 email: `john.smith@example.com`,
904 isActive: true,
905 team: `team1`,
906 },
907 })
908 syncCommit!()
909​
910 await waitForAngularUpdate()
911​
912 // Data should be visible even though still loading
913 expect(state().size).toBe(1)
914 expect(isLoading()).toBe(true) // Still loading
915 expect(data()).toHaveLength(1)
916 expect(data()[0]).toMatchObject({
917 id: `1`,
918 name: `John Smith`,
919 })
920​
921 // Add second batch of data
922 syncBegin!()
923 syncWrite!({
924 type: `insert`,
925 value: {
926 id: `2`,
927 name: `Jane Doe`,
928 age: 32,
929 email: `jane.doe@example.com`,
930 isActive: true,
931 team: `team2`,
932 },
933 })
934 syncCommit!()
935​
936 await waitForAngularUpdate()
937​
938 // More data should be visible
939 expect(state().size).toBe(2)
940 expect(isLoading()).toBe(true) // Still loading
941 expect(data()).toHaveLength(2)
942​
943 // Now mark as ready
944 syncMarkReady!()
945​
946 await waitForAngularUpdate()
947​
948 // Should now be ready
949 expect(isLoading()).toBe(false)
950 expect(state().size).toBe(2)
951 expect(data()).toHaveLength(2)
952 })
953 })
954​
955 it(`should show filtered results during sync with isLoading true`, async () => {
956 await TestBed.runInInjectionContext(async () => {
957 let syncBegin: (() => void) | undefined
958 let syncWrite: ((op: any) => void) | undefined
959 let syncCommit: (() => void) | undefined
960 let syncMarkReady: (() => void) | undefined
961​
962 const collection = createCollection<Person>({
963 id: `eager-filter-test-angular`,
964 getKey: (person: Person) => person.id,
965 startSync: false,
966 sync: {
967 sync: ({ begin, write, commit, markReady }) => {
968 syncBegin = begin
969 syncWrite = write
970 syncCommit = commit
971 syncMarkReady = markReady
972 },
973 },
974 onInsert: () => Promise.resolve(),
975 onUpdate: () => Promise.resolve(),
976 onDelete: () => Promise.resolve(),
977 })
978​
979 const {
980 isLoading,
981 state,
982 data,
983 collection: liveQueryCollection,
984 } = injectLiveQuery({
985 query: (q) =>
986 q
987 .from({ persons: collection })
988 .where(({ persons }) => eq(persons.team, `team1`))
989 .select(({ persons }) => ({
990 id: persons.id,
991 name: persons.name,
992 team: persons.team,
993 })),
994 startSync: false,
995 })
996​
997 // Start the live query sync manually
998 liveQueryCollection()!.preload()
999​
1000 await waitForAngularUpdate()
1001​
1002 expect(isLoading()).toBe(true)
1003​
1004 // Add items from different teams
1005 syncBegin!()
1006 syncWrite!({
1007 type: `insert`,
1008 value: {
1009 id: `1`,
1010 name: `Alice`,
1011 age: 30,
1012 email: `alice@example.com`,
1013 isActive: true,
1014 team: `team1`,
1015 },
1016 })
1017 syncWrite!({
1018 type: `insert`,
1019 value: {
1020 id: `2`,
1021 name: `Bob`,
1022 age: 25,
1023 email: `bob@example.com`,
1024 isActive: true,
1025 team: `team2`,
1026 },
1027 })
1028 syncWrite!({
1029 type: `insert`,
1030 value: {
1031 id: `3`,
1032 name: `Charlie`,
1033 age: 35,
1034 email: `charlie@example.com`,
1035 isActive: true,
1036 team: `team1`,
1037 },
1038 })
1039 syncCommit!()
1040​
1041 await waitForAngularUpdate()
1042​
1043 // Should only show team1 members, even while loading
1044 expect(state().size).toBe(2)
1045 expect(isLoading()).toBe(true)
1046 expect(data()).toHaveLength(2)
1047 expect(data().every((p) => p.team === `team1`)).toBe(true)
1048​
1049 // Mark ready
1050 syncMarkReady!()
1051​
1052 await waitForAngularUpdate()
1053​
1054 expect(isLoading()).toBe(false)
1055 expect(state().size).toBe(2)
1056 })
1057 })
1058​
1059 it(`should update isReady when source collection is marked ready with no data`, async () => {
1060 await TestBed.runInInjectionContext(async () => {
1061 let syncMarkReady: (() => void) | undefined
1062​
1063 const collection = createCollection<Person>({
1064 id: `ready-no-data-test-angular`,
1065 getKey: (person: Person) => person.id,
1066 startSync: false,
1067 sync: {
1068 sync: ({ markReady }) => {
1069 syncMarkReady = markReady
1070 // Don't call begin/commit - just provide markReady
1071 },
1072 },
1073 onInsert: () => Promise.resolve(),
1074 onUpdate: () => Promise.resolve(),
1075 onDelete: () => Promise.resolve(),
1076 })
1077​
1078 const {
1079 isLoading,
1080 isReady,
1081 state,
1082 data,
1083 status,
1084 collection: liveQueryCollection,
1085 } = injectLiveQuery({
1086 query: (q) =>
1088 .from({ persons: collection })
1089 .where(({ persons }) => gt(persons.age, 30))
1090 .select(({ persons }) => ({
1091 id: persons.id,
1092 name: persons.name,
1093 })),
1094 startSync: false,
1095 })
1096​
1097 // Start the live query sync manually
1098 liveQueryCollection()!.preload()
1099​
1100 await waitForAngularUpdate()
1101​
1102 // Now isLoading should be true
1103 expect(isLoading()).toBe(true)
1104 expect(isReady()).toBe(false)
1105 expect(state().size).toBe(0)
1106 expect(data()).toEqual([])
1107​
1108 // Mark ready without any data commits
1109 syncMarkReady!()
1110​
1111 await waitForAngularUpdate()
1112​
1113 // Should now be ready, even with no data
1114 expect(isReady()).toBe(true)
1115 expect(isLoading()).toBe(false)
1116 expect(state().size).toBe(0) // Still no data
1117 expect(data()).toEqual([]) // Empty array
1118 expect(status()).toBe(`ready`)
1119 })
1120 })
1121 })
1122​
1123 describe(`disabled queries`, () => {
1124 it(`should handle query function returning undefined with proper state`, async () => {
1125 await TestBed.runInInjectionContext(async () => {
1126 const collection = createCollection(
1127 mockSyncCollectionOptions<Person>({
1128 id: `disabled-test-undefined-angular`,
1129 getKey: (person: Person) => person.id,
1130 initialData: initialPersons,
1131 }),
1133​
1134 const enabled = signal(false)
1135​
1136 const result = injectLiveQuery({
1137 params: () => ({ enabled: enabled() }),
1138 query: ({ params, q }) => {
1139 if (!params.enabled) return undefined
1140 return q
1141 .from({ persons: collection })
1142 .where(({ persons }) => eq(persons.isActive, true))
1143 .select(({ persons }) => ({
1144 id: persons.id,
1145 name: persons.name,
1146 }))
1147 },
1148 })
1149​
1150 await waitForAngularUpdate()
1151​
1152 // When disabled, status should be 'disabled' and isReady should be true
1153 expect(result.status()).toBe(`disabled`)
1154 expect(result.isReady()).toBe(true)
1155 expect(result.isLoading()).toBe(false)
1156 expect(result.isIdle()).toBe(false)
1157 expect(result.isError()).toBe(false)
1158 expect(result.collection()).toBeNull()
1159 expect(result.data()).toEqual([])
1160 expect(result.state().size).toBe(0)
1161​
1162 // Enable the query
1163 enabled.set(true)
1164 await waitForAngularUpdate()
1165​
1166 // Should now be ready with data
1167 expect(result.status()).toBe(`ready`)
1168 expect(result.isReady()).toBe(true)
1169 expect(result.isLoading()).toBe(false)
1170 expect(result.collection()).not.toBeNull()
1171 expect(result.data().length).toBeGreaterThan(0)
1172 })
1173 })
1174​
1175 it(`should handle query function returning null with proper state`, async () => {
1176 await TestBed.runInInjectionContext(async () => {
1177 const collection = createCollection(
1178 mockSyncCollectionOptions<Person>({
1179 id: `disabled-test-null-angular`,
1180 getKey: (person: Person) => person.id,
1181 initialData: initialPersons,
1182 }),
1184​
1185 const enabled = signal(false)
1186​
1187 const result = injectLiveQuery({
1188 params: () => ({ enabled: enabled() }),
1189 query: ({ params, q }) => {
1190 if (!params.enabled) return null
1191 return q
1192 .from({ persons: collection })
1193 .where(({ persons }) => gt(persons.age, 25))
1194 .select(({ persons }) => ({
1195 id: persons.id,
1196 name: persons.name,
1197 age: persons.age,
1198 }))
1199 },
1200 })
1201​
1202 await waitForAngularUpdate()
1203​
1204 // When disabled, status should be 'disabled' and isReady should be true
1205 expect(result.status()).toBe(`disabled`)
1206 expect(result.isReady()).toBe(true)
1207 expect(result.isLoading()).toBe(false)
1208 expect(result.isIdle()).toBe(false)
1209 expect(result.isError()).toBe(false)
1210 expect(result.collection()).toBeNull()
1211 expect(result.data()).toEqual([])
1212 expect(result.state().size).toBe(0)
1213​
1214 // Enable the query
1215 enabled.set(true)
1216 await waitForAngularUpdate()
1217​
1218 // Should now be ready with data
1219 expect(result.status()).toBe(`ready`)
1220 expect(result.isReady()).toBe(true)
1221 expect(result.isLoading()).toBe(false)
1222 expect(result.collection()).not.toBeNull()
1223 expect(result.data().length).toBeGreaterThan(0)
1224​
1225 // Disable again
1226 enabled.set(false)
1227 await waitForAngularUpdate()
1228​
1229 // Should go back to disabled state
1230 expect(result.status()).toBe(`disabled`)
1231 expect(result.isReady()).toBe(true)
1232 expect(result.collection()).toBeNull()
1233 expect(result.data()).toEqual([])
1234 })
1235 })
1236 })