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

inject-live-query.test.ts

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