Open History to see the last commit
1import { Component, computed, input, inputBinding, signal } from '@angular/core'
2import { TestBed } from '@angular/core/testing'
3import { beforeEach, describe, expect, it, vi } from 'vitest'
4import { injectExternalStore } from '../inject-external-store'
5import { provideAngularQueryChangeDetection } from '../../__tests__/test-utils'
6import type { Signal } from '@angular/core'
7β
8function store(initial: number) {
9 let current = initial
10 const listeners = new Set<() => void>()
11 const cleanup = vi.fn((notify: () => void) => listeners.delete(notify))
12 const subscribe = vi.fn((notify: () => void) => {
13 listeners.add(notify)
14 return () => cleanup(notify)
15 })
16 return {
17 subscribe,
18 cleanup,
19 getSnapshot: () => current,
20 set(next: number) {
21 current = next
22 listeners.forEach((notify) => notify())
23 },
24 }
25}
26β
27function host<T>(
28 create: () => Signal<T>,
29 initialize?: (value: Signal<T>) => void,
30) {
31 @Component({ template: '' })
32 class Host {
33 readonly value = create()
34 ngOnInit() {
35 initialize?.(this.value)
36 }
37 }
38 return TestBed.createComponent(Host)
39}
40β
41describe('injectExternalStore', () => {
42 beforeEach(() => {
43 TestBed.configureTestingModule({
44 providers: [provideAngularQueryChangeDetection()],
45 })
46 })
47β
48 it('reflects changes made during initialization after an early snapshot read', () => {
49 const source = store(1)
50 const fixture = host(
51 () => injectExternalStore(() => source),
52 (value) => {
53 expect(value()).toBe(1)
54 source.set(2)
55 },
56 )
57 fixture.detectChanges()
58 expect(fixture.componentInstance.value()).toBe(2)
59 source.set(3)
60 expect(fixture.componentInstance.value()).toBe(3)
61 })
62β
63 it.each([false, true])(
64 'reflects changes made by subscription setup (notifies: %s)',
65 (notifies) => {
66 const source = store(1)
67 const fixture = host(() =>
68 injectExternalStore(() => ({
69 getSnapshot: source.getSnapshot,
70 subscribe: (notify) => {
71 source.set(2)
72 if (notifies) notify()
73 return source.subscribe(notify)
74 },
75 })),
76 )
77 fixture.detectChanges()
78 expect(fixture.componentInstance.value()).toBe(2)
79 source.set(3)
80 expect(fixture.componentInstance.value()).toBe(3)
81 },
82 )
83β
84 it('preserves equal snapshots for consumers', () => {
85 const source = store(1)
86 const fixture = host(() =>
87 injectExternalStore(
88 () => ({
89 getSnapshot: () => ({ count: source.getSnapshot() }),
90 subscribe: source.subscribe,
91 }),
92 { equal: (a, b) => a.count === b.count },
93 ),
94 )
95 fixture.detectChanges()
96 const derive = vi.fn(() => fixture.componentInstance.value().count)
97 const derived = computed(derive)
98 expect(derived()).toBe(1)
99 source.set(1)
100 expect(derived()).toBe(1)
101 expect(derive).toHaveBeenCalledOnce()
102 source.set(2)
103 expect(derived()).toBe(2)
104 })
105β
106 it('tracks snapshot dependencies without reconnecting for selectors or incidental reads', () => {
107 const source = store(0)
108 const multiplier = signal(10)
109 const incidental = signal(0)
110 const fixture = host(() =>
111 injectExternalStore(() => ({
112 getSnapshot: () => (source.getSnapshot() > 0 ? multiplier() : 0),
113 subscribe: (notify) => {
114 incidental()
115 return source.subscribe(notify)
116 },
117 })),
118 )
119 fixture.detectChanges()
120 const value = fixture.componentInstance.value
121 expect(value()).toBe(0)
122 source.set(1)
123 expect(value()).toBe(10)
124 multiplier.set(20)
125 incidental.set(1)
126 fixture.detectChanges()
127 expect(value()).toBe(20)
128 expect(source.subscribe).toHaveBeenCalledOnce()
129 })
130β
131 it('follows the current source and releases the previous source', () => {
132 const first = store(1)
133 const second = store(10)
134 const requested = signal(first)
135 const fixture = host(() => injectExternalStore(() => requested()))
136 fixture.detectChanges()
137 const value = fixture.componentInstance.value
138 expect(value()).toBe(1)
139 requested.set(second)
140 expect(value()).toBe(10)
141 second.set(11)
142 fixture.detectChanges()
143 expect(value()).toBe(11)
144 expect(first.cleanup).toHaveBeenCalledOnce()
145 first.set(2)
146 expect(value()).toBe(11)
147 second.set(12)
148 expect(value()).toBe(12)
149 })
150β
151 it('releases observation while paused and catches up on resume', () => {
152 const source = store(1)
153 const paused = signal(false)
154 const fixture = host(() =>
155 injectExternalStore(() => ({
156 getSnapshot: source.getSnapshot,
157 subscribe: paused() ? undefined : source.subscribe,
158 })),
159 )
160 fixture.detectChanges()
161 paused.set(true)
162 fixture.detectChanges()
163 expect(source.cleanup).toHaveBeenCalledOnce()
164 source.set(2)
165 paused.set(false)
166 fixture.detectChanges()
167 expect(fixture.componentInstance.value()).toBe(2)
168 source.set(3)
169 expect(fixture.componentInstance.value()).toBe(3)
170 })
171β
172 it('allows subscription setup and cleanup to read the result', () => {
173 const source = store(1)
174 const enabled = signal(true)
175 const seen: Array<number> = []
176 const fixture = host(() => {
177 const value = injectExternalStore(() => ({
178 getSnapshot: source.getSnapshot,
179 subscribe: enabled()
180 ? (notify: () => void) => {
181 seen.push(value())
182 const cleanup = source.subscribe(notify)
183 return () => {
184 seen.push(value())
185 cleanup()
186 }
187 }
188 : undefined,
189 }))
190 return value
191 })
192 fixture.detectChanges()
193 enabled.set(false)
194 fixture.detectChanges()
195 expect(seen).toEqual([1, 1])
196 })
197β
198 it('keeps snapshot errors separate from subscription errors', () => {
199 const source = store(1)
200 const fixture = host(() =>
201 injectExternalStore(() => ({
202 getSnapshot: source.getSnapshot,
203 subscribe: () => {
204 source.set(2)
205 throw new Error('subscribe failed')
206 },
207 })),
208 )
209 expect(() => fixture.detectChanges()).toThrow('subscribe failed')
210 expect(fixture.componentInstance.value()).toBe(2)
211 })
212β
213 it('recovers from a snapshot error on the next store notification', () => {
214 const source = store(1)
215 const fixture = host(() =>
216 injectExternalStore(() => ({
217 getSnapshot: () => {
218 if (source.getSnapshot() === 2) throw new Error('snapshot failed')
219 return source.getSnapshot()
220 },
221 subscribe: source.subscribe,
222 })),
223 )
224 fixture.detectChanges()
225 source.set(2)
226 expect(() => fixture.componentInstance.value()).toThrow('snapshot failed')
227 source.set(3)
228 expect(fixture.componentInstance.value()).toBe(3)
229 expect(source.subscribe).toHaveBeenCalledOnce()
230 })
231β
232 it.each([false, true])(
233 'releases subscriptions on destruction (during setup: %s)',
234 (duringSetup) => {
235 const source = store(1)
236 const fixture = host(() =>
237 injectExternalStore(() => ({
238 getSnapshot: source.getSnapshot,
239 subscribe: (notify) => {
240 const cleanup = source.subscribe(notify)
241 if (duringSetup) fixture.destroy()
242 return cleanup
243 },
244 })),
245 )
246 fixture.detectChanges()
247 if (!duringSetup) fixture.destroy()
248 expect(source.cleanup).toHaveBeenCalledOnce()
249 },
250 )
251β
252 it('renders required inputs and changes made in ngOnInit', () => {
253 const source = store(1)
254 @Component({ template: '{{ value() }}' })
255 class Example {
256 readonly source = input.required<ReturnType<typeof store>>()
257 readonly value = injectExternalStore(() => this.source())
258 ngOnInit() {
259 expect(this.value()).toBe(1)
260 this.source().set(2)
261 }
262 }
263 const fixture = TestBed.createComponent(Example, {
264 bindings: [inputBinding('source', () => source)],
265 })
266 fixture.detectChanges()
267 expect(fixture.nativeElement.textContent).toBe('2')
268 source.set(3)
269 fixture.detectChanges()
270 expect(fixture.nativeElement.textContent).toBe('3')
271 })
272})