-
Notifications
You must be signed in to change notification settings - Fork 714
/
container.test.ts
1175 lines (883 loc) · 38.8 KB
/
container.test.ts
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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { assert, expect } from 'chai';
import * as sinon from 'sinon';
import { inject } from '../../src/annotation/inject';
import { injectable } from '../../src/annotation/injectable';
import { postConstruct } from '../../src/annotation/post_construct';
import * as ERROR_MSGS from '../../src/constants/error_msgs';
import { BindingScopeEnum } from '../../src/constants/literal_types';
import { Container } from '../../src/container/container';
import { ContainerModule } from '../../src/container/container_module';
import { ModuleActivationStore } from '../../src/container/module_activation_store';
import { interfaces } from '../../src/interfaces/interfaces';
import { getBindingDictionary } from '../../src/planning/planner';
import { getServiceIdentifierAsString } from '../../src/utils/serialization';
type Dictionary = Map<interfaces.ServiceIdentifier, interfaces.Binding<unknown>[]>;
describe('Container', () => {
let sandbox: sinon.SinonSandbox;
beforeEach(() => {
sandbox = sinon.createSandbox();
});
afterEach(() => {
sandbox.restore();
});
it('Should be able to use modules as configuration', () => {
interface Ninja { }
interface Katana { }
interface Shuriken { }
@injectable()
class Katana implements Katana { }
@injectable()
class Shuriken implements Shuriken { }
@injectable()
class Ninja implements Ninja { }
const warriors = new ContainerModule((bind: interfaces.Bind) => {
bind<Ninja>('Ninja').to(Ninja);
});
const weapons = new ContainerModule((bind: interfaces.Bind) => {
bind<Katana>('Katana').to(Katana);
bind<Shuriken>('Shuriken').to(Shuriken);
});
const container = new Container();
container.load(warriors, weapons);
let map: Dictionary = getBindingDictionary(container).getMap();
expect(map.has('Ninja')).equal(true);
expect(map.has('Katana')).equal(true);
expect(map.has('Shuriken')).equal(true);
expect(map.size).equal(3);
const tryGetNinja = () => { container.get('Ninja'); };
const tryGetKatana = () => { container.get('Katana'); };
const tryGetShuruken = () => { container.get('Shuriken'); };
container.unload(warriors);
map = getBindingDictionary(container).getMap();
expect(map.size).equal(2);
expect(tryGetNinja).to.throw(ERROR_MSGS.NOT_REGISTERED);
expect(tryGetKatana).not.to.throw();
expect(tryGetShuruken).not.to.throw();
container.unload(weapons);
map = getBindingDictionary(container).getMap();
expect(map.size).equal(0);
expect(tryGetNinja).to.throw(ERROR_MSGS.NOT_REGISTERED);
expect(tryGetKatana).to.throw(ERROR_MSGS.NOT_REGISTERED);
expect(tryGetShuruken).to.throw(ERROR_MSGS.NOT_REGISTERED);
});
it('Should be able to store bindings', () => {
interface Ninja { }
@injectable()
class Ninja implements Ninja { }
const ninjaId = 'Ninja';
const container = new Container();
container.bind<Ninja>(ninjaId).to(Ninja);
const map: Dictionary = getBindingDictionary(container).getMap();
expect(map.size).equal(1);
expect(map.has(ninjaId)).equal(true);
});
it('Should have an unique identifier', () => {
const container1 = new Container();
const container2 = new Container();
expect(container1.id).to.be.a('number');
expect(container2.id).to.be.a('number');
expect(container1.id).not.equal(container2.id);
});
it('Should unbind a binding when requested', () => {
interface Ninja { }
@injectable()
class Ninja implements Ninja { }
const ninjaId = 'Ninja';
const container = new Container();
container.bind<Ninja>(ninjaId).to(Ninja);
const map: Dictionary = getBindingDictionary(container).getMap();
expect(map.has(ninjaId)).equal(true);
container.unbind(ninjaId);
expect(map.has(ninjaId)).equal(false);
expect(map.size).equal(0);
});
it('Should throw when cannot unbind', () => {
const serviceIdentifier = 'Ninja';
const container = new Container();
const throwFunction = () => { container.unbind(serviceIdentifier); };
expect(throwFunction).to.throw(`${ERROR_MSGS.CANNOT_UNBIND} ${getServiceIdentifierAsString(serviceIdentifier)}`);
});
it('Should throw when cannot unbind (async)', async () => {
const serviceIdentifier = 'Ninja';
const container = new Container();
try {
await container.unbindAsync(serviceIdentifier);
assert.fail();
} catch (err: unknown) {
expect((err as Error).message).to.eql(`${ERROR_MSGS.CANNOT_UNBIND} ${getServiceIdentifierAsString(serviceIdentifier)}`);
}
});
it('Should unbind a binding when requested', () => {
interface Ninja { }
@injectable()
class Ninja implements Ninja { }
interface Samurai { }
@injectable()
class Samurai implements Samurai { }
const ninjaId = 'Ninja';
const samuraiId = 'Samurai';
const container = new Container();
container.bind<Ninja>(ninjaId).to(Ninja);
container.bind<Samurai>(samuraiId).to(Samurai);
let map: Dictionary = getBindingDictionary(container).getMap();
expect(map.size).equal(2);
expect(map.has(ninjaId)).equal(true);
expect(map.has(samuraiId)).equal(true);
container.unbind(ninjaId);
map = getBindingDictionary(container).getMap();
expect(map.size).equal(1);
});
it('Should be able unbound all dependencies', () => {
interface Ninja { }
@injectable()
class Ninja implements Ninja { }
interface Samurai { }
@injectable()
class Samurai implements Samurai { }
const ninjaId = 'Ninja';
const samuraiId = 'Samurai';
const container = new Container();
container.bind<Ninja>(ninjaId).to(Ninja);
container.bind<Samurai>(samuraiId).to(Samurai);
let map: Dictionary = getBindingDictionary(container).getMap();
expect(map.size).equal(2);
expect(map.has(ninjaId)).equal(true);
expect(map.has(samuraiId)).equal(true);
container.unbindAll();
map = getBindingDictionary(container).getMap();
expect(map.size).equal(0);
});
it('Should NOT be able to get unregistered services', () => {
interface Ninja { }
@injectable()
class Ninja implements Ninja { }
const ninjaId = 'Ninja';
const container = new Container();
const throwFunction = () => { container.get<Ninja>(ninjaId); };
expect(throwFunction).to.throw(`${ERROR_MSGS.NOT_REGISTERED} ${ninjaId}`);
});
it('Should NOT be able to get ambiguous match', () => {
interface Warrior { }
@injectable()
class Ninja implements Warrior { }
@injectable()
class Samurai implements Warrior { }
const warriorId = 'Warrior';
const container = new Container();
container.bind<Warrior>(warriorId).to(Ninja);
container.bind<Warrior>(warriorId).to(Samurai);
const dictionary: Dictionary = getBindingDictionary(container).getMap();
expect(dictionary.size).equal(1);
dictionary.forEach((value, key) => {
expect(key).equal(warriorId);
expect(value.length).equal(2);
});
const throwFunction = () => { container.get<Warrior>(warriorId); };
expect(throwFunction).to.throw(`${ERROR_MSGS.AMBIGUOUS_MATCH} ${warriorId}`);
});
it('Should NOT be able to getAll of an unregistered services', () => {
interface Ninja { }
@injectable()
class Ninja implements Ninja { }
const ninjaId = 'Ninja';
const container = new Container();
const throwFunction = () => { container.getAll<Ninja>(ninjaId); };
expect(throwFunction).to.throw(`${ERROR_MSGS.NOT_REGISTERED} ${ninjaId}`);
});
it('Should be able to get a string literal identifier as a string', () => {
const Katana = 'Katana';
const KatanaStr = getServiceIdentifierAsString(Katana);
expect(KatanaStr).to.equal('Katana');
});
it('Should be able to get a symbol identifier as a string', () => {
const KatanaSymbol = Symbol.for('Katana');
const KatanaStr = getServiceIdentifierAsString(KatanaSymbol);
expect(KatanaStr).to.equal('Symbol(Katana)');
});
it('Should be able to get a class identifier as a string', () => {
class Katana { }
const KatanaStr = getServiceIdentifierAsString(Katana);
expect(KatanaStr).to.equal('Katana');
});
it('Should be able to snapshot and restore container', () => {
interface Warrior {
}
@injectable()
class Ninja implements Warrior { }
@injectable()
class Samurai implements Warrior { }
const container = new Container();
container.bind<Warrior>(Ninja).to(Ninja);
container.bind<Warrior>(Samurai).to(Samurai);
expect(container.get(Samurai)).to.be.instanceOf(Samurai);
expect(container.get(Ninja)).to.be.instanceOf(Ninja);
container.snapshot(); // snapshot container = v1
container.unbind(Ninja);
expect(container.get(Samurai)).to.be.instanceOf(Samurai);
expect(() => container.get(Ninja)).to.throw();
container.snapshot(); // snapshot container = v2
expect(() => container.get(Ninja)).to.throw();
container.bind<Warrior>(Ninja).to(Ninja);
expect(container.get(Samurai)).to.be.instanceOf(Samurai);
expect(container.get(Ninja)).to.be.instanceOf(Ninja);
container.restore(); // restore container to v2
expect(container.get(Samurai)).to.be.instanceOf(Samurai);
expect(() => container.get(Ninja)).to.throw();
container.restore(); // restore container to v1
expect(container.get(Samurai)).to.be.instanceOf(Samurai);
expect(container.get(Ninja)).to.be.instanceOf(Ninja);
expect(() => container.restore()).to.throw(ERROR_MSGS.NO_MORE_SNAPSHOTS_AVAILABLE);
});
it('Should maintain the activation state of a singleton when doing a snapshot of a container', () => {
let timesCalled = 0;
@injectable()
class Ninja {
@postConstruct()
public postConstruct() {
timesCalled++;
}
}
const container = new Container();
container.bind<Ninja>(Ninja).to(Ninja).inSingletonScope();
container.get<Ninja>(Ninja);
container.snapshot();
container.restore();
container.get<Ninja>(Ninja);
expect(timesCalled).to.be.equal(1);
});
it('Should save and restore the container activations and deactivations when snapshot and restore', () => {
const sid = 'sid';
const container = new Container();
container.bind<string>(sid).toConstantValue('Value');
let activated = false;
let deactivated = false
container.snapshot();
container.onActivation<string>(sid, (c, i) => {
activated = true;
return i;
});
container.onDeactivation(sid, i => {
deactivated = true;
});
container.restore();
container.get(sid);
container.unbind(sid);
expect(activated).to.equal(false);
expect(deactivated).to.equal(false);
})
it('Should save and restore the module activation store when snapshot and restore', () => {
const container = new Container();
const clonedActivationStore = new ModuleActivationStore();
const originalActivationStore = {
clone() {
return clonedActivationStore;
}
}
const anyContainer: any = container;
anyContainer._moduleActivationStore = originalActivationStore;
container.snapshot();
const snapshot = anyContainer._snapshots[0] as interfaces.ContainerSnapshot;
expect(snapshot.moduleActivationStore === clonedActivationStore).to.equal(true);
container.restore();
expect(anyContainer._moduleActivationStore === clonedActivationStore).to.equal(true);
})
it('Should be able to check is there are bindings available for a given identifier', () => {
interface Warrior { }
const warriorId = 'Warrior';
const warriorSymbol = Symbol.for('Warrior');
@injectable()
class Ninja implements Warrior { }
const container = new Container();
container.bind<Warrior>(Ninja).to(Ninja);
container.bind<Warrior>(warriorId).to(Ninja);
container.bind<Warrior>(warriorSymbol).to(Ninja);
expect(container.isBound(Ninja)).equal(true);
expect(container.isBound(warriorId)).equal(true);
expect(container.isBound(warriorSymbol)).equal(true);
interface Katana { }
const katanaId = 'Katana';
const katanaSymbol = Symbol.for('Katana');
@injectable()
class Katana implements Katana { }
expect(container.isBound(Katana)).equal(false);
expect(container.isBound(katanaId)).equal(false);
expect(container.isBound(katanaSymbol)).equal(false);
});
it('Should be able to check is there are bindings available for a given identifier only in current container', () => {
interface Warrior { }
@injectable()
class Ninja implements Warrior { }
const containerParent = new Container();
const containerChild = new Container();
containerChild.parent = containerParent;
containerParent.bind<Warrior>(Ninja).to(Ninja);
expect(containerParent.isBound(Ninja)).to.eql(true);
expect(containerParent.isCurrentBound(Ninja)).to.eql(true);
expect(containerChild.isBound(Ninja)).to.eql(true);
expect(containerChild.isCurrentBound(Ninja)).to.eql(false);
});
it('Should be able to get services from parent container', () => {
const weaponIdentifier = 'Weapon';
@injectable()
class Katana { }
const container = new Container();
container.bind(weaponIdentifier).to(Katana);
const childContainer = new Container();
childContainer.parent = container;
const secondChildContainer = new Container();
secondChildContainer.parent = childContainer;
expect(secondChildContainer.get(weaponIdentifier)).to.be.instanceOf(Katana);
});
it('Should be able to check if services are bound from parent container', () => {
const weaponIdentifier = 'Weapon';
@injectable()
class Katana { }
const container = new Container();
container.bind(weaponIdentifier).to(Katana);
const childContainer = new Container();
childContainer.parent = container;
const secondChildContainer = new Container();
secondChildContainer.parent = childContainer;
expect(secondChildContainer.isBound(weaponIdentifier)).to.be.equal(true);
});
it('Should prioritize requested container to resolve a service identifier', () => {
const weaponIdentifier = 'Weapon';
@injectable()
class Katana { }
@injectable()
class DivineRapier { }
const container = new Container();
container.bind(weaponIdentifier).to(Katana);
const childContainer = new Container();
childContainer.parent = container;
const secondChildContainer = new Container();
secondChildContainer.parent = childContainer;
secondChildContainer.bind(weaponIdentifier).to(DivineRapier);
expect(secondChildContainer.get(weaponIdentifier)).to.be.instanceOf(DivineRapier);
});
it('Should be able to resolve named multi-injection', () => {
interface Intl {
hello?: string;
goodbye?: string;
}
const container = new Container();
container.bind<Intl>('Intl').toConstantValue({ hello: 'bonjour' }).whenTargetNamed('fr');
container.bind<Intl>('Intl').toConstantValue({ goodbye: 'au revoir' }).whenTargetNamed('fr');
container.bind<Intl>('Intl').toConstantValue({ hello: 'hola' }).whenTargetNamed('es');
container.bind<Intl>('Intl').toConstantValue({ goodbye: 'adios' }).whenTargetNamed('es');
const fr = container.getAllNamed<Intl>('Intl', 'fr');
expect(fr.length).to.equal(2);
expect(fr[0]?.hello).to.equal('bonjour');
expect(fr[1]?.goodbye).to.equal('au revoir');
const es = container.getAllNamed<Intl>('Intl', 'es');
expect(es.length).to.equal(2);
expect(es[0]?.hello).to.equal('hola');
expect(es[1]?.goodbye).to.equal('adios');
});
it('Should be able to resolve tagged multi-injection', () => {
interface Intl {
hello?: string;
goodbye?: string;
}
const container = new Container();
container.bind<Intl>('Intl').toConstantValue({ hello: 'bonjour' }).whenTargetTagged('lang', 'fr');
container.bind<Intl>('Intl').toConstantValue({ goodbye: 'au revoir' }).whenTargetTagged('lang', 'fr');
container.bind<Intl>('Intl').toConstantValue({ hello: 'hola' }).whenTargetTagged('lang', 'es');
container.bind<Intl>('Intl').toConstantValue({ goodbye: 'adios' }).whenTargetTagged('lang', 'es');
const fr = container.getAllTagged<Intl>('Intl', 'lang', 'fr');
expect(fr.length).to.equal(2);
expect(fr[0]?.hello).to.equal('bonjour');
expect(fr[1]?.goodbye).to.equal('au revoir');
const es = container.getAllTagged<Intl>('Intl', 'lang', 'es');
expect(es.length).to.equal(2);
expect(es[0]?.hello).to.equal('hola');
expect(es[1]?.goodbye).to.equal('adios');
});
it('Should be able configure the default scope at a global level', () => {
interface Warrior {
health: number;
takeHit(damage: number): void;
}
@injectable()
class Ninja implements Warrior {
public health: number;
public constructor() {
this.health = 100;
}
public takeHit(damage: number) {
this.health = this.health - damage;
}
}
const TYPES = {
Warrior: 'Warrior'
};
const container1 = new Container();
container1.bind<Warrior>(TYPES.Warrior).to(Ninja);
const transientNinja1 = container1.get<Warrior>(TYPES.Warrior);
expect(transientNinja1.health).to.equal(100);
transientNinja1.takeHit(10);
expect(transientNinja1.health).to.equal(90);
const transientNinja2 = container1.get<Warrior>(TYPES.Warrior);
expect(transientNinja2.health).to.equal(100);
transientNinja2.takeHit(10);
expect(transientNinja2.health).to.equal(90);
const container2 = new Container({ defaultScope: BindingScopeEnum.Singleton });
container2.bind<Warrior>(TYPES.Warrior).to(Ninja);
const singletonNinja1 = container2.get<Warrior>(TYPES.Warrior);
expect(singletonNinja1.health).to.equal(100);
singletonNinja1.takeHit(10);
expect(singletonNinja1.health).to.equal(90);
const singletonNinja2 = container2.get<Warrior>(TYPES.Warrior);
expect(singletonNinja2.health).to.equal(90);
singletonNinja2.takeHit(10);
expect(singletonNinja2.health).to.equal(80);
});
it('Should default binding scope to Transient if no default scope on options', () => {
const container = new Container();
container.options.defaultScope = undefined;
const expectedScope: interfaces.BindingScope = 'Transient';
expect((container.bind('SID') as unknown as { _binding: { scope: interfaces.BindingScope } })._binding.scope).to.equal(expectedScope);
});
it('Should be able to configure automatic binding for @injectable() decorated classes', () => {
@injectable()
class Katana { }
@injectable()
class Shuriken { }
@injectable()
class Ninja {
public constructor(public weapon: Katana) { }
}
class Samurai { }
const container1 = new Container({ autoBindInjectable: true });
const katana1 = container1.get(Katana);
const ninja1 = container1.get(Ninja);
expect(katana1).to.be.an.instanceof(Katana);
expect(katana1).to.not.equal(container1.get(Katana));
expect(ninja1).to.be.an.instanceof(Ninja);
expect(ninja1).to.not.equal(container1.get(Ninja));
expect(ninja1.weapon).to.be.an.instanceof(Katana);
expect(ninja1.weapon).to.not.equal(container1.get(Ninja).weapon);
expect(ninja1.weapon).to.not.equal(katana1);
const container2 = new Container({ defaultScope: BindingScopeEnum.Singleton, autoBindInjectable: true });
const katana2 = container2.get(Katana);
const ninja2 = container2.get(Ninja);
expect(katana2).to.be.an.instanceof(Katana);
expect(katana2).to.equal(container2.get(Katana));
expect(ninja2).to.be.an.instanceof(Ninja);
expect(ninja2).to.equal(container2.get(Ninja));
expect(ninja2.weapon).to.be.an.instanceof(Katana);
expect(ninja2.weapon).to.equal(container2.get(Ninja).weapon);
expect(ninja2.weapon).to.equal(katana2);
const container3 = new Container({ autoBindInjectable: true });
container3.bind(Katana).toSelf().inSingletonScope();
const katana3 = container3.get(Katana);
const ninja3 = container3.get(Ninja);
expect(katana3).to.be.an.instanceof(Katana);
expect(katana3).to.equal(container3.get(Katana));
expect(ninja3).to.be.an.instanceof(Ninja);
expect(ninja3).to.not.equal(container3.get(Ninja));
expect(ninja3.weapon).to.be.an.instanceof(Katana);
expect(ninja3.weapon).to.equal(container3.get(Ninja).weapon);
expect(ninja3.weapon).to.equal(katana3);
const container4 = new Container({ autoBindInjectable: true });
container4.bind(Katana).to(Shuriken);
const katana4 = container4.get(Katana);
const ninja4 = container4.get(Ninja);
expect(katana4).to.be.an.instanceof(Shuriken);
expect(katana4).to.not.equal(container4.get(Katana));
expect(ninja4).to.be.an.instanceof(Ninja);
expect(ninja4).to.not.equal(container4.get(Ninja));
expect(ninja4.weapon).to.be.an.instanceof(Shuriken);
expect(ninja4.weapon).to.not.equal(container4.get(Ninja).weapon);
expect(ninja4.weapon).to.not.equal(katana4);
const container5 = new Container({ autoBindInjectable: true });
expect(() => container5.get(Samurai)).to.throw(ERROR_MSGS.NOT_REGISTERED);
});
it('Should be throw an exception if incorrect options is provided', () => {
const invalidOptions1 = () => 0;
const wrong1 = () => new Container(invalidOptions1 as unknown as interfaces.ContainerOptions);
expect(wrong1).to.throw(`${ERROR_MSGS.CONTAINER_OPTIONS_MUST_BE_AN_OBJECT}`);
const invalidOptions2 = { autoBindInjectable: 'wrongValue' };
const wrong2 = () => new Container(invalidOptions2 as unknown as interfaces.ContainerOptions);
expect(wrong2).to.throw(`${ERROR_MSGS.CONTAINER_OPTIONS_INVALID_AUTO_BIND_INJECTABLE}`);
const invalidOptions3 = { defaultScope: 'wrongValue' };
const wrong3 = () => new Container(invalidOptions3 as unknown as interfaces.ContainerOptions);
expect(wrong3).to.throw(`${ERROR_MSGS.CONTAINER_OPTIONS_INVALID_DEFAULT_SCOPE}`);
});
it('Should be able to merge two containers', () => {
@injectable()
class Ninja {
public name = 'Ninja';
}
@injectable()
class Shuriken {
public name = 'Shuriken';
}
const CHINA_EXPANSION_TYPES = {
Ninja: 'Ninja',
Shuriken: 'Shuriken'
};
const chinaExpansionContainer = new Container();
chinaExpansionContainer.bind<Ninja>(CHINA_EXPANSION_TYPES.Ninja).to(Ninja);
chinaExpansionContainer.bind<Shuriken>(CHINA_EXPANSION_TYPES.Shuriken).to(Shuriken);
@injectable()
class Samurai {
public name = 'Samurai';
}
@injectable()
class Katana {
public name = 'Katana';
}
const JAPAN_EXPANSION_TYPES = {
Katana: 'Katana',
Samurai: 'Samurai'
};
const japanExpansionContainer = new Container();
japanExpansionContainer.bind<Samurai>(JAPAN_EXPANSION_TYPES.Samurai).to(Samurai);
japanExpansionContainer.bind<Katana>(JAPAN_EXPANSION_TYPES.Katana).to(Katana);
const gameContainer = Container.merge(chinaExpansionContainer, japanExpansionContainer);
expect(gameContainer.get<Ninja>(CHINA_EXPANSION_TYPES.Ninja).name).to.equal('Ninja');
expect(gameContainer.get<Shuriken>(CHINA_EXPANSION_TYPES.Shuriken).name).to.equal('Shuriken');
expect(gameContainer.get<Samurai>(JAPAN_EXPANSION_TYPES.Samurai).name).to.equal('Samurai');
expect(gameContainer.get<Katana>(JAPAN_EXPANSION_TYPES.Katana).name).to.equal('Katana');
});
it('Should be able to merge multiple containers', () => {
@injectable()
class Ninja {
public name = 'Ninja';
}
@injectable()
class Shuriken {
public name = 'Shuriken';
}
const CHINA_EXPANSION_TYPES = {
Ninja: 'Ninja',
Shuriken: 'Shuriken'
};
const chinaExpansionContainer = new Container();
chinaExpansionContainer.bind<Ninja>(CHINA_EXPANSION_TYPES.Ninja).to(Ninja);
chinaExpansionContainer.bind<Shuriken>(CHINA_EXPANSION_TYPES.Shuriken).to(Shuriken);
@injectable()
class Samurai {
public name = 'Samurai';
}
@injectable()
class Katana {
public name = 'Katana';
}
const JAPAN_EXPANSION_TYPES = {
Katana: 'Katana',
Samurai: 'Samurai'
};
const japanExpansionContainer = new Container();
japanExpansionContainer.bind<Samurai>(JAPAN_EXPANSION_TYPES.Samurai).to(Samurai);
japanExpansionContainer.bind<Katana>(JAPAN_EXPANSION_TYPES.Katana).to(Katana);
@injectable()
class Sheriff {
public name = 'Sheriff';
}
@injectable()
class Revolver {
public name = 'Revolver';
}
const USA_EXPANSION_TYPES = {
Revolver: 'Revolver',
Sheriff: 'Sheriff'
};
const usaExpansionContainer = new Container();
usaExpansionContainer.bind<Sheriff>(USA_EXPANSION_TYPES.Sheriff).to(Sheriff);
usaExpansionContainer.bind<Revolver>(USA_EXPANSION_TYPES.Revolver).to(Revolver);
const gameContainer = Container.merge(chinaExpansionContainer, japanExpansionContainer, usaExpansionContainer);
expect(gameContainer.get<Ninja>(CHINA_EXPANSION_TYPES.Ninja).name).to.equal('Ninja');
expect(gameContainer.get<Shuriken>(CHINA_EXPANSION_TYPES.Shuriken).name).to.equal('Shuriken');
expect(gameContainer.get<Samurai>(JAPAN_EXPANSION_TYPES.Samurai).name).to.equal('Samurai');
expect(gameContainer.get<Katana>(JAPAN_EXPANSION_TYPES.Katana).name).to.equal('Katana');
expect(gameContainer.get<Sheriff>(USA_EXPANSION_TYPES.Sheriff).name).to.equal('Sheriff');
expect(gameContainer.get<Revolver>(USA_EXPANSION_TYPES.Revolver).name).to.equal('Revolver');
});
it('Should be able create a child containers', () => {
const parent = new Container();
const child = parent.createChild();
if (child.parent === null) {
throw new Error('Parent should not be null');
}
expect(child.parent.id).to.equal(parent.id);
});
it('Should inherit parent container options', () => {
@injectable()
class Warrior { }
const parent = new Container({
defaultScope: BindingScopeEnum.Singleton
});
const child = parent.createChild();
child.bind(Warrior).toSelf();
const singletonWarrior1 = child.get(Warrior);
const singletonWarrior2 = child.get(Warrior);
expect(singletonWarrior1).to.equal(singletonWarrior2);
});
it('Should be able to override options to child containers', () => {
@injectable()
class Warrior { }
const parent = new Container({
defaultScope: BindingScopeEnum.Request
});
const child = parent.createChild({
defaultScope: BindingScopeEnum.Singleton
});
child.bind(Warrior).toSelf();
const singletonWarrior1 = child.get(Warrior);
const singletonWarrior2 = child.get(Warrior);
expect(singletonWarrior1).to.equal(singletonWarrior2);
});
it('Should be able check if a named binding is bound', () => {
const zero = 'Zero';
const invalidDivisor = 'InvalidDivisor';
const validDivisor = 'ValidDivisor';
const container = new Container();
expect(container.isBound(zero)).to.equal(false);
container.bind<number>(zero).toConstantValue(0);
expect(container.isBound(zero)).to.equal(true);
container.unbindAll();
expect(container.isBound(zero)).to.equal(false);
container.bind<number>(zero).toConstantValue(0).whenTargetNamed(invalidDivisor);
expect(container.isBoundNamed(zero, invalidDivisor)).to.equal(true);
expect(container.isBoundNamed(zero, validDivisor)).to.equal(false);
container.bind<number>(zero).toConstantValue(1).whenTargetNamed(validDivisor);
expect(container.isBoundNamed(zero, invalidDivisor)).to.equal(true);
expect(container.isBoundNamed(zero, validDivisor)).to.equal(true);
});
it('Should be able to check if a named binding is bound from parent container', () => {
const zero = 'Zero';
const invalidDivisor = 'InvalidDivisor';
const validDivisor = 'ValidDivisor';
const container = new Container();
const childContainer = container.createChild();
const secondChildContainer = childContainer.createChild();
container.bind<number>(zero).toConstantValue(0).whenTargetNamed(invalidDivisor);
expect(secondChildContainer.isBoundNamed(zero, invalidDivisor)).to.equal(true);
expect(secondChildContainer.isBoundNamed(zero, validDivisor)).to.equal(false);
container.bind<number>(zero).toConstantValue(1).whenTargetNamed(validDivisor);
expect(secondChildContainer.isBoundNamed(zero, invalidDivisor)).to.equal(true);
expect(secondChildContainer.isBoundNamed(zero, validDivisor)).to.equal(true);
});
it('Should be able to get a tagged binding', () => {
const zero = 'Zero';
const isValidDivisor = 'IsValidDivisor';
const container = new Container();
container.bind<number>(zero).toConstantValue(0).whenTargetTagged(isValidDivisor, false);
expect(container.getTagged(zero, isValidDivisor, false)).to.equal(0);
container.bind<number>(zero).toConstantValue(1).whenTargetTagged(isValidDivisor, true);
expect(container.getTagged(zero, isValidDivisor, false)).to.equal(0);
expect(container.getTagged(zero, isValidDivisor, true)).to.equal(1);
});
it('Should be able to get a tagged binding from parent container', () => {
const zero = 'Zero';
const isValidDivisor = 'IsValidDivisor';
const container = new Container();
const childContainer = container.createChild();
const secondChildContainer = childContainer.createChild();
container.bind<number>(zero).toConstantValue(0).whenTargetTagged(isValidDivisor, false);
container.bind<number>(zero).toConstantValue(1).whenTargetTagged(isValidDivisor, true);
expect(secondChildContainer.getTagged(zero, isValidDivisor, false)).to.equal(0);
expect(secondChildContainer.getTagged(zero, isValidDivisor, true)).to.equal(1);
});
it('Should be able check if a tagged binding is bound', () => {
const zero = 'Zero';
const isValidDivisor = 'IsValidDivisor';
const container = new Container();
expect(container.isBound(zero)).to.equal(false);
container.bind<number>(zero).toConstantValue(0);
expect(container.isBound(zero)).to.equal(true);
container.unbindAll();
expect(container.isBound(zero)).to.equal(false);
container.bind<number>(zero).toConstantValue(0).whenTargetTagged(isValidDivisor, false);
expect(container.isBoundTagged(zero, isValidDivisor, false)).to.equal(true);
expect(container.isBoundTagged(zero, isValidDivisor, true)).to.equal(false);
container.bind<number>(zero).toConstantValue(1).whenTargetTagged(isValidDivisor, true);
expect(container.isBoundTagged(zero, isValidDivisor, false)).to.equal(true);
expect(container.isBoundTagged(zero, isValidDivisor, true)).to.equal(true);
});
it('Should be able to check if a tagged binding is bound from parent container', () => {
const zero = 'Zero';
const isValidDivisor = 'IsValidDivisor';
const container = new Container();
const childContainer = container.createChild();
const secondChildContainer = childContainer.createChild();
container.bind<number>(zero).toConstantValue(0).whenTargetTagged(isValidDivisor, false);
expect(secondChildContainer.isBoundTagged(zero, isValidDivisor, false)).to.equal(true);
expect(secondChildContainer.isBoundTagged(zero, isValidDivisor, true)).to.equal(false);
container.bind<number>(zero).toConstantValue(1).whenTargetTagged(isValidDivisor, true);
expect(secondChildContainer.isBoundTagged(zero, isValidDivisor, false)).to.equal(true);
expect(secondChildContainer.isBoundTagged(zero, isValidDivisor, true)).to.equal(true);
});
it('Should be able to override a binding using rebind', () => {
const TYPES = {
someType: 'someType'
};
const container = new Container();
container.bind<number>(TYPES.someType).toConstantValue(1);
container.bind<number>(TYPES.someType).toConstantValue(2);
const values1 = container.getAll(TYPES.someType);
expect(values1[0]).to.eq(1);
expect(values1[1]).to.eq(2);
container.rebind<number>(TYPES.someType).toConstantValue(3);
const values2 = container.getAll(TYPES.someType);
expect(values2[0]).to.eq(3);
expect(values2[1]).to.eq(undefined);
});
it('Should be able to override a binding using rebindAsync', async () => {
const TYPES = {
someType: 'someType'
};
const container = new Container();
container.bind<number>(TYPES.someType).toConstantValue(1);
container.bind<number>(TYPES.someType).toConstantValue(2);
container.onDeactivation(TYPES.someType, () => Promise.resolve())
const values1 = container.getAll(TYPES.someType);
expect(values1[0]).to.eq(1);
expect(values1[1]).to.eq(2);
(await container.rebindAsync<number>(TYPES.someType)).toConstantValue(3);
const values2 = container.getAll(TYPES.someType);
expect(values2[0]).to.eq(3);