Repository navigation
Expand file tree
/
Copy pathsignal-store.spec.ts
More file actions
766 lines (651 loc) · 22.3 KB
/
Copy pathsignal-store.spec.ts
File metadata and controls
766 lines (651 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
import {
computed,
inject,
InjectionToken,
isSignal,
linkedSignal,
signal,
} from '@angular/core';
import { TestBed } from '@angular/core/testing';
import {
patchState,
signalStore,
signalStoreFeature,
withComputed,
withHooks,
withLinkedState,
withMethods,
withProps,
withState,
} from '../src';
import { STATE_SOURCE } from '../src/state-source';
import { assertStateSource, createLocalService } from './helpers';
describe('signalStore', () => {
const consoleWarnSpy = vi.spyOn(console, 'warn');
consoleWarnSpy.mockImplementation(() => void true);
beforeEach(() => {
consoleWarnSpy.mockClear();
});
describe('creation', () => {
it('creates a store via new operator', () => {
const Store = signalStore(withState({ foo: 'bar' }));
const store = new Store();
expect(store.foo()).toBe('bar');
});
it('creates a store as injectable service', () => {
const Store = signalStore(withState({ foo: 'bar' }));
TestBed.configureTestingModule({ providers: [Store] });
const store = TestBed.inject(Store);
expect(store.foo()).toBe('bar');
});
it('creates a store that is provided in root when providedIn option is root', () => {
const Store = signalStore(
{ providedIn: 'root' },
withState({ foo: 'bar' })
);
const store1 = TestBed.inject(Store);
const store2 = TestBed.inject(Store);
expect(store1).toBe(store2);
expect(store1.foo()).toBe('bar');
});
it('creates a store with state source as Record holding slices as signals by default', () => {
const Store = signalStore(withState({ foo: 'bar' }));
const store = new Store();
const stateSource = store[STATE_SOURCE];
expect(isSignal(stateSource)).toBe(false);
expect(Object.keys(stateSource)).toEqual(['foo']);
expect(isSignal(stateSource.foo)).toBe(true);
assertStateSource(stateSource, {
foo: signal('bar'),
});
});
it('creates a store with state source as Record holding slices as signals when protectedState option is true', () => {
const Store = signalStore(
{ protectedState: true },
withState({ foo: 'bar' })
);
const store = new Store();
const stateSource = store[STATE_SOURCE];
expect(isSignal(stateSource)).toBe(false);
expect(Object.keys(stateSource)).toEqual(['foo']);
expect(isSignal(stateSource.foo)).toBe(true);
assertStateSource(stateSource, {
foo: signal('bar'),
});
});
it('creates a store with state source as Record holding slices as writeable signals when protectedState option is false', () => {
const Store = signalStore(
{ protectedState: false },
withState({ foo: 'bar' })
);
const store = new Store();
const stateSource = store[STATE_SOURCE];
expect(isSignal(stateSource)).toBe(false);
expect(Object.keys(stateSource)).toEqual(['foo']);
expect(isSignal(stateSource.foo)).toBe(true);
assertStateSource(stateSource, {
foo: signal('bar'),
});
expect(typeof stateSource.foo.update === 'function').toBe(true);
patchState(store, { foo: 'baz' });
assertStateSource(stateSource, {
foo: signal('baz'),
});
});
});
describe('withState', () => {
it('adds deep signals to the store for each state slice', () => {
const Store = signalStore(
withState({
foo: 'foo',
x: { y: { z: 10 } },
})
);
const store = new Store();
assertStateSource(store[STATE_SOURCE], {
foo: signal('foo'),
x: signal({ y: { z: 10 } }),
});
expect(store.foo()).toBe('foo');
expect(store.x()).toEqual({ y: { z: 10 } });
expect(store.x.y()).toEqual({ z: 10 });
expect(store.x.y.z()).toBe(10);
});
it('supports a state slice that is a union of an object, undefined, and a primitive', () => {
const Store = signalStore(
{ protectedState: false },
withState<{ slice: { n: number } | undefined | number }>({
slice: { n: 1 },
})
);
const store = new Store();
expect(isSignal(store.slice)).toBe(true);
expect(store.slice()).toEqual({ n: 1 });
expect('n' in store.slice).toBe(true);
expect('n' in store.slice && store.slice.n()).toBe(1);
patchState(store, { slice: undefined });
expect(store.slice()).toBe(undefined);
expect('n' in store.slice).toBe(false);
patchState(store, { slice: 42 });
expect(store.slice()).toBe(42);
expect('n' in store.slice).toBe(false);
});
it('overrides Function properties if nested state keys have the same name', () => {
const Store = signalStore(
withState({ name: { length: { name: false } } })
);
const store = new Store();
expect(store.name()).toEqual({ length: { name: false } });
expect(isSignal(store.name)).toBe(true);
expect(store.name.length()).toEqual({ name: false });
expect(isSignal(store.name.length)).toBe(true);
expect(store.name.length.name()).toBe(false);
expect(isSignal(store.name.length.name)).toBe(true);
});
it('does not create signals for optional state slices without initial value', () => {
type State = { x?: number; y?: { z: number } };
const Store = signalStore(
{ protectedState: false },
withState<State>({ x: 10 })
);
const store = new Store();
expect(store.x!()).toBe(10);
expect(store.y).toBe(undefined);
patchState(store, { y: { z: 100 } });
expect(store.y).toBe(undefined);
});
it('executes withState factory in injection context', () => {
const TOKEN = new InjectionToken('TOKEN', {
providedIn: 'root',
factory: () => ({ foo: 'foo' }),
});
const Store = signalStore(withState(() => inject(TOKEN)));
TestBed.configureTestingModule({ providers: [Store] });
const store = TestBed.inject(Store);
expect(store.foo()).toBe('foo');
});
it('allows symbols as state keys', () => {
const SECRET = Symbol('SECRET');
const Store = signalStore(withState({ [SECRET]: 'bar' }));
const store = new Store();
expect(store[SECRET]()).toBe('bar');
});
});
describe('withLinkedState', () => {
describe('updates automatically if the source changes', () =>
[
{
name: 'with computed function',
linkedStateFeature: signalStoreFeature(
withState({ userId: 1 }),
withLinkedState(({ userId }) => ({
books: () => {
userId();
return [] as string[];
},
}))
),
},
{
name: 'with explicit linkedSignal',
linkedStateFeature: signalStoreFeature(
withState({ userId: 1 }),
withLinkedState(({ userId }) => ({
books: linkedSignal({
source: userId,
computation: () => [] as string[],
}),
}))
),
},
].forEach(({ name, linkedStateFeature }) => {
it(name, () => {
const BookStore = signalStore(
{ providedIn: 'root', protectedState: false },
linkedStateFeature,
withState({ version: 1 }),
withMethods((store) => ({
updateUser() {
patchState(store, (value) => value);
patchState(store, ({ userId }) => ({ userId: userId + 1 }));
},
addBook(title: string) {
patchState(store, ({ books }) => ({
books: [...books, title],
}));
},
increaseVersion() {
patchState(store, ({ version }) => ({ version: version + 1 }));
},
}))
);
const bookStore = TestBed.inject(BookStore);
bookStore.addBook('The Neverending Story');
bookStore.increaseVersion();
expect(bookStore.books()).toEqual(['The Neverending Story']);
expect(bookStore.version()).toEqual(2);
patchState(bookStore, { userId: 2 });
expect(bookStore.books()).toEqual([]);
expect(bookStore.version()).toEqual(2);
});
}));
describe('can depend on a Signal from another SignalStore', () => {
const UserStore = signalStore(
{ providedIn: 'root', protectedState: false },
withState({ userId: 1 })
);
[
{
name: 'with computation function',
linkedStateFeature: signalStoreFeature(
withLinkedState((_, userStore = inject(UserStore)) => ({
books: () => {
userStore.userId();
return [] as string[];
},
}))
),
},
{
name: 'with explicit linkedSignal',
linkedStateFeature: signalStoreFeature(
withLinkedState(() => {
const userStore = inject(UserStore);
return {
books: linkedSignal({
source: userStore.userId,
computation: () => [] as string[],
}),
};
})
),
},
].forEach(({ name, linkedStateFeature }) => {
it(name, () => {
const BookStore = signalStore(
{ providedIn: 'root' },
linkedStateFeature,
withMethods((store) => ({
addBook(title: string) {
patchState(store, ({ books }) => ({
books: [...books, title],
}));
},
}))
);
const userStore = TestBed.inject(UserStore);
const bookStore = TestBed.inject(BookStore);
bookStore.addBook('The Neverending Story');
expect(bookStore.books()).toEqual(['The Neverending Story']);
patchState(userStore, { userId: 2 });
expect(bookStore.books()).toEqual([]);
});
});
});
it('links user-defined writable signals', () => {
const user = signal({ name: 'Mark' });
const UserStore = signalStore(
{ providedIn: 'root' },
withLinkedState(() => ({ user })),
withMethods((store) => ({
setUserName(name: string): void {
patchState(store, { user: { name } });
},
}))
);
const userStore = TestBed.inject(UserStore);
expect(userStore.user()).toEqual({ name: 'Mark' });
userStore.setUserName('John');
expect(userStore.user()).toEqual({ name: 'John' });
expect(user()).toEqual({ name: 'John' });
user.set({ name: 'Tom' });
expect(userStore.user()).toEqual({ name: 'Tom' });
expect(user()).toEqual({ name: 'Tom' });
});
it('has access to state signals', () => {
const UserStore = signalStore(
{ providedIn: 'root' },
withState({ userId: 1 }),
withLinkedState(({ userId }) => ({ value: userId }))
);
const userStore = TestBed.inject(UserStore);
expect(userStore.value()).toBe(1);
});
it('has access to props', () => {
const UserStore = signalStore(
{ providedIn: 'root' },
withProps(() => ({ userId: 1 })),
withLinkedState(({ userId }) => ({ value: () => userId }))
);
const userStore = TestBed.inject(UserStore);
expect(userStore.value()).toBe(1);
});
});
describe('withProps', () => {
it('provides previously defined state slices and properties as input argument', () => {
const Store = signalStore(
withState(() => ({ foo: 'foo' })),
withComputed(() => ({ bar: signal('bar').asReadonly() })),
withProps(() => ({ num: 10 })),
withProps(({ foo, bar, num }) => {
expect(foo()).toBe('foo');
expect(bar()).toBe('bar');
expect(num).toBe(10);
return { baz: num + 1 };
})
);
const store = new Store();
assertStateSource(store[STATE_SOURCE], {
foo: signal('foo'),
});
expect(store.foo()).toBe('foo');
expect(store.bar()).toBe('bar');
expect(store.num).toBe(10);
expect(store.baz).toBe(11);
});
it('executes withProps factory in injection context', () => {
const TOKEN = new InjectionToken('TOKEN', {
providedIn: 'root',
factory: () => ({ foo: 'bar' }),
});
const Store = signalStore(withProps(() => inject(TOKEN)));
TestBed.configureTestingModule({ providers: [Store] });
const store = TestBed.inject(Store);
expect(store.foo).toBe('bar');
});
it('allows symbols as property keys', () => {
const SECRET = Symbol('SECRET');
const Store = signalStore(withProps(() => ({ [SECRET]: 'secret' })));
const store = TestBed.configureTestingModule({
providers: [Store],
}).inject(Store);
expect(store[SECRET]).toBe('secret');
});
it('allows numbers as property keys', () => {
const Store = signalStore(withProps(() => ({ 1: 'Number One' })));
const store = TestBed.configureTestingModule({
providers: [Store],
}).inject(Store);
expect(store[1]).toBe('Number One');
});
});
describe('withComputed', () => {
it('provides previously defined state slices and properties as input argument', () => {
const Store = signalStore(
withState(() => ({ foo: 'foo' })),
withComputed(() => ({ bar: signal('bar').asReadonly() })),
withProps(() => ({ num: 10 })),
withComputed(({ foo, bar, num }) => {
expect(foo()).toBe('foo');
expect(bar()).toBe('bar');
expect(num).toBe(10);
return { baz: signal('baz').asReadonly() };
})
);
const store = new Store();
assertStateSource(store[STATE_SOURCE], {
foo: signal('foo'),
});
expect(store.foo()).toBe('foo');
expect(store.bar()).toBe('bar');
expect(store.num).toBe(10);
expect(store.baz()).toBe('baz');
});
it('executes withComputed factory in injection context', () => {
const TOKEN = new InjectionToken('TOKEN', {
providedIn: 'root',
factory: () => ({ bar: signal('bar').asReadonly() }),
});
const Store = signalStore(withComputed(() => inject(TOKEN)));
TestBed.configureTestingModule({ providers: [Store] });
const store = TestBed.inject(Store);
expect(store.bar()).toBe('bar');
});
it('allows symbols as computed keys', () => {
const SECRET = Symbol('SECRET');
const SecretStore = signalStore(
{ providedIn: 'root' },
withComputed(() => ({
[SECRET]: computed(() => 'secret'),
}))
);
const secretStore = TestBed.inject(SecretStore);
expect(secretStore[SECRET]()).toBe('secret');
});
});
describe('withMethods', () => {
it('provides previously defined store properties as an input argument', () => {
const Store = signalStore(
withState(() => ({ foo: 'foo' })),
withComputed(() => ({ bar: signal('bar').asReadonly() })),
withMethods(() => ({ baz: () => 'baz' })),
withProps(() => ({ num: 100 })),
withMethods((store) => {
assertStateSource(store[STATE_SOURCE], {
foo: signal('foo'),
});
expect(store.foo()).toBe('foo');
expect(store.bar()).toBe('bar');
expect(store.baz()).toBe('baz');
expect(store.num).toBe(100);
return { m: () => 'm' };
})
);
const store = new Store();
assertStateSource(store[STATE_SOURCE], {
foo: signal('foo'),
});
expect(store.foo()).toBe('foo');
expect(store.bar()).toBe('bar');
expect(store.baz()).toBe('baz');
expect(store.num).toBe(100);
expect(store.m()).toBe('m');
});
it('executes withMethods factory in injection context', () => {
const TOKEN = new InjectionToken('TOKEN', {
providedIn: 'root',
factory: () => ({ baz: () => 'baz' }),
});
const Store = signalStore(withMethods(() => inject(TOKEN)));
TestBed.configureTestingModule({ providers: [Store] });
const store = TestBed.inject(Store);
expect(store.baz()).toBe('baz');
});
it('allows symbols as method keys', () => {
const SECRET = Symbol('SECRET');
const SecretStore = signalStore(
{ providedIn: 'root' },
withMethods(() => ({
[SECRET]: () => 'my secret',
}))
);
const secretStore = TestBed.inject(SecretStore);
expect(secretStore[SECRET]()).toBe('my secret');
});
});
describe('withHooks', () => {
it('calls onInit hook on store init', () => {
let message = '';
const Store = signalStore(
withHooks({
onInit() {
message = 'onInit';
},
})
);
new Store();
expect(message).toBe('onInit');
message = '';
TestBed.configureTestingModule({ providers: [Store] });
TestBed.inject(Store);
expect(message).toBe('onInit');
});
it('calls onDestroy hook on store destroy', () => {
let message = '';
const Store = signalStore(
withHooks({
onDestroy() {
message = 'onDestroy';
},
})
);
createLocalService(Store).destroy();
expect(message).toBe('onDestroy');
});
it('provides previously defined store properties as onInit input argument', () => {
let message = '';
const Store = signalStore(
withState(() => ({ foo: 'foo' })),
withComputed(() => ({ bar: signal('bar').asReadonly() })),
withMethods(() => ({ baz: () => 'baz' })),
withProps(() => ({ num: 10 })),
withHooks({
onInit(store) {
assertStateSource(store[STATE_SOURCE], {
foo: signal('foo'),
});
expect(store.foo()).toBe('foo');
expect(store.bar()).toBe('bar');
expect(store.baz()).toBe('baz');
expect(store.num).toBe(10);
message = 'onInit';
},
})
);
new Store();
expect(message).toBe('onInit');
});
it('provides previously defined store properties as onDestroy input argument', () => {
let message = '';
const Store = signalStore(
withState(() => ({ foo: 'foo' })),
withComputed(() => ({ bar: signal('bar').asReadonly() })),
withMethods(() => ({ baz: () => 'baz' })),
withProps(() => ({ num: 100 })),
withHooks({
onDestroy(store) {
expect(store.foo()).toBe('foo');
expect(store.bar()).toBe('bar');
expect(store.baz()).toBe('baz');
expect(store.num).toBe(100);
message = 'onDestroy';
},
})
);
createLocalService(Store).destroy();
expect(message).toBe('onDestroy');
});
it('executes hooks factory in injection context', () => {
const messages: string[] = [];
const TOKEN_INIT = new InjectionToken('TOKEN_INIT', {
providedIn: 'root',
factory: () => 'init',
});
const TOKEN_DESTROY = new InjectionToken('TOKEN_DESTROY', {
providedIn: 'root',
factory: () => 'destroy',
});
const Store = signalStore(
withState({ name: 'NgRx Store' }),
withHooks((store) => {
const tokenInit = inject(TOKEN_INIT);
const tokenDestroy = inject(TOKEN_DESTROY);
return {
onInit() {
messages.push(`${tokenInit} ${store.name()}`);
},
onDestroy() {
messages.push(`${tokenDestroy} ${store.name()}`);
},
};
})
);
const { destroy } = createLocalService(Store);
expect(messages).toEqual(['init NgRx Store']);
destroy();
expect(messages).toEqual(['init NgRx Store', 'destroy NgRx Store']);
});
it('executes onInit hook in injection context', () => {
const messages: string[] = [];
const TOKEN = new InjectionToken('TOKEN', {
providedIn: 'root',
factory: () => 'init',
});
const Store = signalStore(
withState({ name: 'NgRx Store' }),
withHooks({
onInit(store, token = inject(TOKEN)) {
messages.push(`${token} ${store.name()}`);
},
})
);
TestBed.configureTestingModule({ providers: [Store] });
TestBed.inject(Store);
expect(messages).toEqual(['init NgRx Store']);
});
it('succeeds with onDestroy and providedIn: root', () => {
const messages: string[] = [];
const Store = signalStore(
{ providedIn: 'root' },
withHooks({
onDestroy() {
messages.push('ending...');
},
})
);
TestBed.inject(Store);
TestBed.resetTestingModule();
expect(messages).toEqual(['ending...']);
});
});
describe('composition', () => {
it('logs warning if previously defined signal store members have the same name', () => {
const Store = signalStore(
withState({ i: 1, j: 2, k: 3, l: 4 }),
withComputed(() => ({
l: signal('l').asReadonly(),
m: signal('m').asReadonly(),
})),
withMethods(() => ({
j: () => 'j',
m: () => true,
n: (value: number) => value,
}))
);
new Store();
expect(consoleWarnSpy).toHaveBeenCalledTimes(2);
expect(consoleWarnSpy.mock.calls).toEqual([
[
'@ngrx/signals: SignalStore members cannot be overridden.',
'Trying to override:',
'l',
],
[
'@ngrx/signals: SignalStore members cannot be overridden.',
'Trying to override:',
'j, m',
],
]);
});
it('passes on a symbol key to the features', () => {
const SECRET = Symbol('SECRET');
const SecretStore = signalStore(
withProps(() => ({
[SECRET]: 'not your business',
})),
withComputed((store) => ({
secret: computed(() => store[SECRET]),
})),
withMethods((store) => ({
reveil() {
return store[SECRET];
},
}))
);
const secretStore = new SecretStore();
expect(secretStore.reveil()).toBe('not your business');
expect(secretStore.secret()).toBe('not your business');
expect(secretStore[SECRET]).toBe('not your business');
});
});
});