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} 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 QueryBuilder,
18} from "@tanstack/db"
19
20// Import the same test utilities as Vue
21
22type Person = {
23 id: string
24 name: string
25 age: number
26 email: string
27 isActive: boolean
28 team: string
29}
30
31const initialPersons: Array<Person> = [
32 {
33 id: `1`,
34 name: `John Doe`,
35 age: 30,
36 email: `john.doe@example.com`,
37 isActive: true,
38 team: `team1`,
39 },
40 {
41 id: `2`,
42 name: `Jane Doe`,
43 age: 25,
44 email: `jane.doe@example.com`,
45 isActive: true,
46 team: `team2`,
47 },
48 {
49 id: `3`,
50 name: `John Smith`,
51 age: 35,
52 email: `john.smith@example.com`,
53 isActive: true,
54 team: `team1`,
55 },
56]
57
58// Helper function to wait for Angular effects and collection updates
59async function waitForAngularUpdate() {
60 // Wait for Angular change detection
61 await new Promise((resolve) => setTimeout(resolve, 0))
62 // Additional delay for collection updates
63 await new Promise((resolve) => setTimeout(resolve, 50))
64}
65
66function createMockCollection<T extends object, K extends string | number>(
67 initial: Array<T & Record<`id`, K>> = [],
68 initialStatus: CollectionStatus = `ready`
69): Collection<T, K, Record<string, never>> & {
70 __setStatus: (s: CollectionStatus) => void
71 __replaceAll: (rows: Array<T & Record<`id`, K>>) => void
72 __upsert: (row: T & Record<`id`, K>) => void
73 __delete: (key: K) => void
74} {
75 const map = new Map<K, T>()
76 for (const r of initial) {
77 map.set(r.id, r)
78 }
79
80 let status: CollectionStatus = initialStatus
81 const subs = new Set<(changes: Array<any>) => void>()
82 const readySubs = new Set<() => void>()
83 const id = `mock-col-` + Math.random().toString(36).slice(2)
84
85 const notify = (changes: Array<any> = []) => {
86 for (const cb of subs) cb(changes)
87 }
88
89 const notifyReady = () => {
90 for (const cb of readySubs) cb()
91 }
92
93 const api: any = {
94 id,
95 get status() {
96 return status
97 },
98 entries: () => Array.from(map.entries()),
99 values: () => Array.from(map.values()),
100 get: (key: K) => map.get(key),
101 has: (key: K) => map.has(key),
102 size: () => map.size,
103 subscribeChanges: (cb: (changes: Array<any>) => void) => {
104 subs.add(cb)
105 return {
106 unsubscribe: () => subs.delete(cb),
107 }
108 },
109 onFirstReady: (cb: () => void) => {
110 if (status === `ready`) {
111 setTimeout(cb, 0)
112 } else {
113 readySubs.add(cb)
114 }
115 return () => readySubs.delete(cb)
116 },
117 preload: () => Promise.resolve(),
118 startSyncImmediate: () => {
119 const wasNotReady = status !== `ready`
120 if (status === `idle`) {
121 status = `ready`
122 }
123 if (wasNotReady && status === `ready`) {
124 setTimeout(notifyReady, 0)
125 }
126 },
127 __setStatus: (s: CollectionStatus) => {
128 const wasNotReady = status !== `ready`
129 status = s
130 notify([])
131 if (wasNotReady && status === `ready`) {
132 setTimeout(notifyReady, 0)
133 }
134 },
135 __replaceAll: (rows: Array<T & Record<`id`, K>>) => {
136 map.clear()
137 for (const r of rows) map.set(r.id, r)
138 notify([])
139 },
140 __upsert: (row: T & Record<`id`, K>) => {
141 const isUpdate = map.has(row.id)
142 map.set(row.id, row)
143 notify([
144 {
145 type: isUpdate ? `update` : `insert`,
146 key: row.id,
147 value: row,
148 },
149 ])
150 },
151 __delete: (key: K) => {
152 map.delete(key)
153 notify([
154 {
155 type: `delete`,
156 key: key,
157 },
158 ])
159 },
160 }
161
162 return api
163}
164
165describe(`injectLiveQuery`, () => {
166 it(`throws if used outside injection context`, () => {
167 expect(() => {
168 injectLiveQuery(() => ({}) as unknown as QueryBuilder<Context>)
169 }).toThrow(
170 /NG0203:|injectLiveQuery\(\) can only be used within an injection context/i
171 )
172 })
173
174 it(`should work with basic collection and select`, async () => {
175 await TestBed.runInInjectionContext(async () => {
176 const collection = createCollection(
177 mockSyncCollectionOptions<Person>({
178 id: `test-persons-angular`,
179 getKey: (person: Person) => person.id,
180 initialData: initialPersons,
181 })
182 )
183
184 const { state, data } = injectLiveQuery((q) =>
185 q
186 .from({ persons: collection })
187 .where(({ persons }) => gt(persons.age, 30))
188 .select(({ persons }) => ({
189 id: persons.id,
190 name: persons.name,
191 age: persons.age,
192 }))
193 )
194
195 await waitForAngularUpdate()
196
197 expect(state().size).toBe(1) // Only John Smith (age 35)
198 expect(data()).toHaveLength(1)
199
200 const johnSmith = data()[0]
201 expect(johnSmith).toMatchObject({
202 id: `3`,
203 name: `John Smith`,
204 age: 35,
205 })
206 })
207 })
208
209 it(`initializes with an existing collection and exposes signals`, async () => {
210 await TestBed.runInInjectionContext(async () => {
211 const col = createMockCollection<{ id: number; name: string }, number>(
212 [{ id: 1, name: `A` }],
213 `ready`
214 )
215
216 const result = injectLiveQuery(col)
217
218 await waitForAngularUpdate()
219
220 expect(result.collection()).toBe(col)
221 expect(result.state().get(1)).toEqual({ id: 1, name: `A` })
222 expect(result.data()).toEqual([{ id: 1, name: `A` }])
223 expect(result.status()).toBe(`ready`)
224 expect(result.isReady()).toBe(true)
225 expect(result.isLoading()).toBe(false)
226 expect(result.isIdle()).toBe(false)
227 expect(result.isError()).toBe(false)
228 expect(result.isCleanedUp()).toBe(false)
229 })
230 })
231
232 it(`subscribes to collection changes and updates signals`, async () => {
233 await TestBed.runInInjectionContext(async () => {
234 const col = createMockCollection<{ id: number; name: string }, number>(
235 [{ id: 1, name: `A` }],
236 `ready`
237 )
238 const result = injectLiveQuery(col)
239
240 await waitForAngularUpdate()
241
242 col.__upsert({ id: 2, name: `B` })
243 await waitForAngularUpdate()
244
245 expect(result.state().get(2)).toEqual({ id: 2, name: `B` })
246 expect(result.data()).toEqual([
247 { id: 1, name: `A` },
248 { id: 2, name: `B` },
249 ])
250
251 col.__delete(1)
252 await waitForAngularUpdate()
253
254 expect(result.state().has(1)).toBe(false)
255 expect(result.data()).toEqual([{ id: 2, name: `B` }])
256
257 col.__replaceAll([{ id: 3, name: `C` }])
258 await waitForAngularUpdate()
259
260 expect(Array.from(result.state().keys())).toEqual([3])
261 expect(result.data()).toEqual([{ id: 3, name: `C` }])
262 })
263 })
264
265 it(`reflects status changes in derived flags`, async () => {
266 await TestBed.runInInjectionContext(async () => {
267 const col = createMockCollection<{ id: number; name: string }, number>(
268 [],
269 `idle`
270 )
271 const { status, isReady, isLoading, isError, isCleanedUp } =
272 injectLiveQuery(col)
273
274 await waitForAngularUpdate()
275
276 expect(status()).toBe(`ready`) // Should be ready after startSyncImmediate
277 expect(isReady()).toBe(true)
278
279 col.__setStatus(`loading`)
280 await waitForAngularUpdate()
281
282 expect(status()).toBe(`loading`)
283 expect(isLoading()).toBe(true)
284
285 col.__setStatus(`error`)
286 await waitForAngularUpdate()
287
288 expect(status()).toBe(`error`)
289 expect(isError()).toBe(true)
290
291 col.__setStatus(`cleaned-up`)
292 await waitForAngularUpdate()
293
294 expect(status()).toBe(`cleaned-up`)
295 expect(isCleanedUp()).toBe(true)
296 })
297 })
298
299 it(`should be able to query a collection with live updates`, async () => {
300 await TestBed.runInInjectionContext(async () => {
301 const collection = createCollection(
302 mockSyncCollectionOptions<Person>({
303 id: `test-persons-2-angular`,
304 getKey: (person: Person) => person.id,
305 initialData: initialPersons,
306 })
307 )
308
309 const { state, data } = injectLiveQuery((q) =>
310 q
311 .from({ collection })
312 .where(({ collection: c }) => gt(c.age, 30))
313 .select(({ collection: c }) => ({
314 id: c.id,
315 name: c.name,
316 }))
317 .orderBy(({ collection: c }) => c.id, `asc`)
318 )
319
320 await waitForAngularUpdate()
321
322 expect(state().size).toBe(1)
323 expect(state().get(`3`)).toMatchObject({
324 id: `3`,
325 name: `John Smith`,
326 })
327
328 expect(data().length).toBe(1)
329 expect(data()[0]).toMatchObject({
330 id: `3`,
331 name: `John Smith`,
332 })
333
334 // Insert a new person using the proper utils pattern
335 collection.utils.begin()
336 collection.utils.write({
337 type: `insert`,
338 value: {
339 id: `4`,
340 name: `Kyle Doe`,
341 age: 40,
342 email: `kyle.doe@example.com`,
343 isActive: true,
344 team: `team1`,
345 },
346 })
347 collection.utils.commit()
348
349 await waitForAngularUpdate()
350
351 expect(state().size).toBe(2)
352 expect(state().get(`3`)).toMatchObject({
353 id: `3`,
354 name: `John Smith`,
355 })
356 expect(state().get(`4`)).toMatchObject({
357 id: `4`,
358 name: `Kyle Doe`,
359 })
360
361 expect(data().length).toBe(2)
362 expect(data()).toEqual(
363 expect.arrayContaining([
364 expect.objectContaining({
365 id: `3`,
366 name: `John Smith`,
367 }),
368 expect.objectContaining({
369 id: `4`,
370 name: `Kyle Doe`,
371 }),
372 ])
373 )
374 })
375 })
376
377 it.todo(
378 `reuses collection when deps are unchanged and query/config are same`,
379 async () => {
380 const collection = createCollection(
381 mockSyncCollectionOptions<Person>({
382 id: `reuse-test-angular`,
383 getKey: (person: Person) => person.id,
384 initialData: initialPersons,
385 })
386 )
387
388 const config: LiveQueryCollectionConfig<Context> = {
389 query: (q) =>
390 q
391 .from({ persons: collection })
392 .where(({ persons }) => gt(persons.age, 30))
393 .select(({ persons }) => ({
394 id: persons.id,
395 name: persons.name,
396 })),
397 startSync: true,
398 gcTime: 0,
399 }
400
401 let col1: any
402 let col2: any
403
404 await TestBed.runInInjectionContext(async () => {
405 const first = injectLiveQuery(config)
406 await waitForAngularUpdate()
407 col1 = first.collection()
408 })
409
410 await TestBed.runInInjectionContext(async () => {
411 const second = injectLiveQuery(config)
412 await waitForAngularUpdate()
413 col2 = second.collection()
414 })
415
416 expect(col2).toBe(col1)
417 }
418 )
419
420 it(`creates a new collection when deps change`, async () => {
421 const collection = createCollection(
422 mockSyncCollectionOptions<Person>({
423 id: `deps-change-test-angular`,
424 getKey: (person: Person) => person.id,
425 initialData: initialPersons,
426 })
427 )
428
429 const config: LiveQueryCollectionConfig<Context> = {
430 query: (q) =>
431 q
432 .from({ persons: collection })
433 .where(({ persons }) => gt(persons.age, 30))
434 .select(({ persons }) => ({
435 id: persons.id,
436 name: persons.name,
437 })),
438 startSync: true,
439 gcTime: 0,
440 }
441
442 let col1: any
443 let col2: any
444
445 await TestBed.runInInjectionContext(async () => {
446 const first = injectLiveQuery(config)
447 await waitForAngularUpdate()
448 col1 = first.collection()
449 })
450
451 await TestBed.runInInjectionContext(async () => {
452 const second = injectLiveQuery({
453 ...config,
454 gcTime: 1,
455 })
456 await waitForAngularUpdate()
457 col2 = second.collection()
458 })
459
460 expect(col2).not.toBe(col1)
461 })
462
463 it(`reuses exact same passed collection instance`, async () => {
464 await TestBed.runInInjectionContext(async () => {
465 const col = createMockCollection<{ id: number; name: string }, number>(
466 [],
467 `ready`
468 )
469
470 const a = injectLiveQuery(col)
471 const b = injectLiveQuery(col)
472
473 await waitForAngularUpdate()
474
475 expect(a.collection()).toBe(col)
476 expect(b.collection()).toBe(col)
477 })
478 })
479
480 it(`cleans up subscription on destroy`, async () => {
481 await TestBed.runInInjectionContext(async () => {
482 const col = createMockCollection<{ id: number; name: string }, number>(
483 [{ id: 1, name: `A` }],
484 `ready`
485 )
486
487 const destroyRef = inject(DestroyRef)
488 const res = injectLiveQuery(col)
489
490 await waitForAngularUpdate()
491
492 col.__upsert({ id: 2, name: `B` })
493 await waitForAngularUpdate()
494
495 expect(res.state().get(2)).toEqual({ id: 2, name: `B` })
496
497 destroyRef.onDestroy(() => {})
498 })
499
500 await TestBed.runInInjectionContext(async () => {
501 const col = createMockCollection<{ id: number; name: string }, number>(
502 [],
503 `ready`
504 )
505 const res = injectLiveQuery(col)
506
507 await waitForAngularUpdate()
508
509 expect(res.data()).toEqual([])
510 })
511 })
512
513 it(`accepts a query function and initializes collection via createLiveQueryCollection`, async () => {
514 await TestBed.runInInjectionContext(async () => {
515 const collection = createCollection(
516 mockSyncCollectionOptions<Person>({
517 id: `query-fn-test-angular`,
518 getKey: (person: Person) => person.id,
519 initialData: initialPersons,
520 })
521 )
522
523 const res = injectLiveQuery((q) =>
524 q
525 .from({ persons: collection })
526 .where(({ persons }) => gt(persons.age, 30))
527 .select(({ persons }) => ({
528 id: persons.id,
529 name: persons.name,
530 }))
531 )
532
533 await waitForAngularUpdate()
534
535 expect(res.collection().id).toEqual(expect.any(String))
536 expect(res.status()).toBe(`ready`)
537 expect(Array.isArray(res.data())).toBe(true)
538 expect(res.state() instanceof Map).toBe(true)
539 })
540 })
541
542 it(`accepts a LiveQueryCollectionConfig object`, async () => {
543 await TestBed.runInInjectionContext(async () => {
544 const collection = createCollection(
545 mockSyncCollectionOptions<Person>({
546 id: `config-test-angular`,
547 getKey: (person: Person) => person.id,
548 initialData: initialPersons,
549 })
550 )
551
552 const config: LiveQueryCollectionConfig<Context> = {
553 query: (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 startSync: true,
562 gcTime: 0,
563 }
564
565 const res = injectLiveQuery(config)
566 await waitForAngularUpdate()
567
568 expect(res.collection().id).toEqual(expect.any(String))
569 expect(res.isReady()).toBe(true)
570 })
571 })
572
573 it(`throws from computed collection if not initialized (defensive path)`, async () => {
574 await TestBed.runInInjectionContext(async () => {
575 const col = createMockCollection<{ id: number; name: string }, number>(
576 [],
577 `ready`
578 )
579 const res = injectLiveQuery(col)
580
581 await waitForAngularUpdate()
582
583 expect(res.collection()).toBe(col)
584 })
585 })
586
587 it(`accepts reactive params with query function`, async () => {
588 await TestBed.runInInjectionContext(async () => {
589 const collection = createCollection(
590 mockSyncCollectionOptions<Person>({
591 id: `reactive-params-test-angular`,
592 getKey: (person: Person) => person.id,
593 initialData: initialPersons,
594 })
595 )
596
597 const projectId = signal(1)
598
599 const res = injectLiveQuery({
600 params: () => ({ projectID: projectId() }),
601 query: ({ params, q }) =>
602 q
603 .from({ persons: collection })
604 .where(({ persons }) => eq(persons.team, `team${params.projectID}`))
605 .select(({ persons }) => ({
606 id: persons.id,
607 name: persons.name,
608 team: persons.team,
609 })),
610 })
611
612 await waitForAngularUpdate()
613
614 expect(res.collection().id).toEqual(expect.any(String))
615 expect(res.status()).toBe(`ready`)
616 expect(Array.isArray(res.data())).toBe(true)
617 expect(res.state() instanceof Map).toBe(true)
618
619 // Should get team1 people (John Doe and John Smith) when projectID is 1
620 expect(res.data()).toHaveLength(2)
621 expect(res.data()).toEqual(
622 expect.arrayContaining([
623 expect.objectContaining({
624 id: `1`,
625 name: `John Doe`,
626 team: `team1`,
627 }),
628 expect.objectContaining({
629 id: `3`,
630 name: `John Smith`,
631 team: `team1`,
632 }),
633 ])
634 )
635
636 projectId.set(2)
637 await waitForAngularUpdate()
638
639 // Should get team2 person (Jane Doe) when projectID is 2
640 expect(res.data()).toHaveLength(1)
641 expect(res.data()[0]).toMatchObject({
642 id: `2`,
643 name: `Jane Doe`,
644 team: `team2`,
645 })
646 })
647 })
648
649 it(`reactive params update when signal changes`, async () => {
650 await TestBed.runInInjectionContext(async () => {
651 const collection = createCollection(
652 mockSyncCollectionOptions<Person>({
653 id: `reactive-update-test-angular`,
654 getKey: (person: Person) => person.id,
655 initialData: initialPersons,
656 })
657 )
658
659 const selectedProjectId = signal(2)
660
661 const res = injectLiveQuery({
662 params: () => ({ projectID: selectedProjectId() }),
663 query: ({ params, q }) =>
664 q
665 .from({ persons: collection })
666 .where(({ persons }) => eq(persons.team, `team${params.projectID}`))
667 .select(({ persons }) => ({
668 id: persons.id,
669 name: persons.name,
670 team: persons.team,
671 })),
672 })
673
674 await waitForAngularUpdate()
675
676 expect(res.isReady()).toBe(true)
677 // Should initially show team2 data
678 expect(res.data()).toHaveLength(1)
679 expect(res.data()[0]).toMatchObject({
680 id: `2`,
681 name: `Jane Doe`,
682 team: `team2`,
683 })
684
685 selectedProjectId.set(1)
686 await waitForAngularUpdate()
687
688 expect(selectedProjectId()).toBe(1)
689 // Should now show team1 data (2 people)
690 expect(res.data()).toHaveLength(2)
691 expect(res.data()).toEqual(
692 expect.arrayContaining([
693 expect.objectContaining({
694 id: `1`,
695 name: `John Doe`,
696 team: `team1`,
697 }),
698 expect.objectContaining({
699 id: `3`,
700 name: `John Smith`,
701 team: `team1`,
702 }),
703 ])
704 )
705 })
706 })
707
708 it(`should accept pre-created live query collection`, async () => {
709 await TestBed.runInInjectionContext(async () => {
710 const collection = createCollection(
711 mockSyncCollectionOptions<Person>({
712 id: `pre-created-collection-test-angular`,
713 getKey: (person: Person) => person.id,
714 initialData: initialPersons,
715 })
716 )
717
718 // Create a live query collection beforehand
719 const liveQueryCollection = createLiveQueryCollection({
720 query: (q) =>
721 q
722 .from({ persons: collection })
723 .where(({ persons }) => gt(persons.age, 30))
724 .select(({ persons }) => ({
725 id: persons.id,
726 name: persons.name,
727 age: persons.age,
728 })),
729 startSync: true,
730 })
731
732 const {
733 state,
734 data,
735 collection: returnedCollection,
736 } = injectLiveQuery(liveQueryCollection)
737
738 await waitForAngularUpdate()
739
740 expect(state().size).toBe(1) // Only John Smith (age 35)
741 expect(data()).toHaveLength(1)
742
743 const johnSmith = data()[0]
744 expect(johnSmith).toMatchObject({
745 id: `3`,
746 name: `John Smith`,
747 age: 35,
748 })
749
750 // Verify that the returned collection is the same instance
751 expect(returnedCollection()).toBe(liveQueryCollection)
752 })
753 })
754})