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

inject-live-query.test.ts

1,212 lines33.6 KB

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