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