-
-
Notifications
You must be signed in to change notification settings - Fork 147
/
di.spec.ts
1237 lines (1023 loc) · 43.8 KB
/
di.spec.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 { expect } from 'chai';
import {
match,
SinonMatcher,
spy
} from 'sinon';
import {
classInvokers,
Container,
Factory,
fallbackInvoker,
invokeWithDynamicDependencies,
Resolver,
ResolverStrategy
} from '../src/di';
import {
Constructable,
DI,
IContainer,
IDefaultableInterfaceSymbol,
inject,
PLATFORM,
Registration,
singleton,
transient
} from '../src/index';
import { _ } from './util';
function assertIsMutableArray(arr: any[], length: number): void {
expect(Array.isArray(arr)).to.equal(true);
expect(arr instanceof Array).to.equal(true);
expect(arr).not.to.equal(PLATFORM.emptyArray);
expect(arr.length).to.equal(length);
arr.push(null);
expect(arr.length).to.equal(length + 1);
arr.pop();
expect(arr.length).to.equal(length);
}
function decorator(): ClassDecorator { return (target: any) => target; }
describe(`The DI object`, function () {
describe(`createContainer()`, function () {
it(`returns an instance of Container`, function () {
const actual = DI.createContainer();
expect(actual).to.be.instanceof(Container);
});
it(`returns a new container every time`, function () {
expect(DI.createContainer()).not.to.equal(DI.createContainer());
});
});
describe(`getDesignParamTypes()`, function () {
it(`returns PLATFORM.emptyArray if the class has no constructor or decorators`, function () {
class Foo {}
const actual = DI.getDesignParamTypes(Foo);
expect(actual).to.equal(PLATFORM.emptyArray);
});
it(`returns PLATFORM.emptyArray if the class has a decorator but no constructor`, function () {
@decorator()
class Foo {}
const actual = DI.getDesignParamTypes(Foo);
expect(actual).to.equal(PLATFORM.emptyArray);
});
it(`returns PLATFORM.emptyArray if the class has no constructor args or decorators`, function () {
class Foo { constructor() { return; } }
const actual = DI.getDesignParamTypes(Foo);
expect(actual).to.equal(PLATFORM.emptyArray);
});
it(`returns PLATFORM.emptyArray if the class has constructor args but no decorators`, function () {
class Bar {}
class Foo { constructor(public bar: Bar) {} }
const actual = DI.getDesignParamTypes(Foo);
expect(actual).to.equal(PLATFORM.emptyArray);
});
it(`returns PLATFORM.emptyArray if the class has constructor args and the decorator is applied via a function call`, function () {
class Bar {}
class Foo { constructor(public bar: Bar) {} }
decorator()(Foo);
const actual = DI.getDesignParamTypes(Foo);
expect(actual).to.equal(PLATFORM.emptyArray);
});
it(`returns PLATFORM.emptyArray if the class is declared as an anonymous variable, even if it has ctor args and decorator is applied properly`, function () {
class Bar {}
// @ts-ignore
@decorator()
const FooInline = class { constructor(public bar: Bar) {} };
const actual = DI.getDesignParamTypes(FooInline);
expect(actual).to.equal(PLATFORM.emptyArray);
});
it(`returns PLATFORM.emptyArray if the class is declared as a named variable, even if it has ctor args and decorator is applied properly`, function () {
class Bar {}
// @ts-ignore
@decorator()
const FooInline = class Foo { constructor(public bar: Bar) {} };
const actual = DI.getDesignParamTypes(FooInline);
expect(actual).to.equal(PLATFORM.emptyArray);
});
describe(`returns an empty array if the class has a decorator but no constructor args`, function () {
@decorator()
class Foo { constructor() { return; } }
it(_`${Foo}`, function () {
const actual = DI.getDesignParamTypes(Foo);
assertIsMutableArray(actual, 0);
});
it(_`${class {}}`, function () {
let cls;
function anonDecorator(): ClassDecorator { return (target: any) => cls = target; }
// @ts-ignore
@anonDecorator()
class { constructor() { return; } }
const actual = DI.getDesignParamTypes(cls);
assertIsMutableArray(actual, 0);
});
});
describe(`falls back to Object for declarations that cannot be statically analyzed`, function () {
interface ArgCtor {}
for (const argCtor of [
class Bar {},
function () { return; },
() => { return; },
class {},
{},
Error,
Array,
(class Bar {}).prototype,
(class Bar {}).prototype.constructor
] as any[]) {
@decorator()
class FooDecoratorInvocation { constructor(public arg: ArgCtor) {} }
it(_`${FooDecoratorInvocation} { constructor(${argCtor}) }`, function () {
const actual = DI.getDesignParamTypes(FooDecoratorInvocation);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Object);
});
@(decorator as any)
class FooDecoratorNonInvocation { constructor(public arg: ArgCtor) {} }
it(_`${FooDecoratorNonInvocation} { constructor(${argCtor}) }`, function () {
const actual = DI.getDesignParamTypes(FooDecoratorInvocation);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Object);
});
}
});
describe(`falls back to Object for mismatched declarations`, function () {
// Technically we're testing TypeScript here, but it's still useful to have an in-place fixture to validate our assumptions
// And also to have an alert mechanism for when the functionality in TypeScript changes, without having to read the changelogs
// What we're verifying here is under which circumstances a function object will or won't be properly resolved as a
// designParamType, and it seems like the presence of a same-name interface actually breaks this in some situations
// Note: the order of declaration (interface first or other thing first) doesn't seem to matter here
// But whether or not there is a direct type cast, does seem to matter in the case of AnonClass (note the negative assertion)
// It's unclear whether the difference between AnonClass (which works) and AnonClassInterface (which doesn't work) is a bug in TS or not,
// but it has ramifications we need to keep in mind.
interface Bar {}
class Bar {}
interface AnonClass {}
const AnonClass = class {};
interface AnonClassInterface {}
const AnonClassInterface: AnonClassInterface = class {};
interface VarFunc {}
const VarFunc = function () { return; };
interface VarFuncInterface {}
const VarFuncInterface: VarFuncInterface = function () { return; };
interface Func {}
// tslint:disable-next-line:no-empty
function Func() {}
interface Arrow {}
const Arrow = () => { return; };
interface ArrowInterface {}
const ArrowInterface: ArrowInterface = () => { return; };
describe(`decorator invocation`, function () {
@decorator()
class FooBar { constructor(public arg: Bar) {} }
// Note: this is a negative assertion meant to make it easier to compare this describe with the one below
it(_`NOT ${FooBar} { constructor(public ${Bar}) }`, function () {
const actual = DI.getDesignParamTypes(FooBar);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Bar);
});
@decorator()
class FooAnonClass { constructor(public arg: AnonClass) {} }
// Note: this is a negative assertion meant to make it easier to compare this describe with the one below
it(_`NOT ${FooAnonClass} { constructor(public ${AnonClass}) }`, function () {
const actual = DI.getDesignParamTypes(FooAnonClass);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(AnonClass);
});
@decorator()
class FooAnonClassInterface { constructor(public arg: AnonClassInterface) {} }
// this one is particularly interesting..
it(_`${FooAnonClassInterface} { constructor(public ${AnonClassInterface}) }`, function () {
const actual = DI.getDesignParamTypes(FooAnonClassInterface);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Object);
});
@decorator()
class FooVarFunc { constructor(public arg: VarFunc) {} }
it(_`${FooVarFunc} { constructor(public ${VarFunc}) }`, function () {
const actual = DI.getDesignParamTypes(FooVarFunc);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Object);
});
@decorator()
class FooVarFuncInterface { constructor(public arg: VarFuncInterface) {} }
it(_`${FooVarFuncInterface} { constructor(public ${VarFuncInterface}) }`, function () {
const actual = DI.getDesignParamTypes(FooVarFuncInterface);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Object);
});
@decorator()
class FooFunc { constructor(public arg: Func) {} }
it(_`${FooFunc} { constructor(public ${Func}) }`, function () {
const actual = DI.getDesignParamTypes(FooFunc);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Object);
});
@decorator()
class FooArrow { constructor(public arg: Arrow) {} }
it(_`${FooArrow} { constructor(public ${Arrow}) }`, function () {
const actual = DI.getDesignParamTypes(FooArrow);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Object);
});
@decorator()
class FooArrowInterface { constructor(public arg: ArrowInterface) {} }
it(_`${FooArrowInterface} { constructor(public ${ArrowInterface}) }`, function () {
const actual = DI.getDesignParamTypes(FooArrowInterface);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Object);
});
});
});
describe(`returns the correct types for valid declarations`, function () {
class Bar {}
const AnonClass = class {};
const VarFunc = function () { return; };
// tslint:disable-next-line:no-empty
function Func() {}
const Arrow = () => { return; };
describe(`decorator invocation`, function () {
@decorator()
class FooBar { constructor(public arg: Bar) {} }
it(_`${FooBar} { constructor(public ${Bar}) }`, function () {
const actual = DI.getDesignParamTypes(FooBar);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Bar);
});
@decorator()
// @ts-ignore
class FooAnonClass { constructor(public arg: AnonClass) {} }
it(_`${FooAnonClass} { constructor(public ${AnonClass}) }`, function () {
const actual = DI.getDesignParamTypes(FooAnonClass);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(AnonClass);
});
@decorator()
// @ts-ignore
class FooVarFunc { constructor(public arg: VarFunc) {} }
it(_`${FooVarFunc} { constructor(public ${VarFunc}) }`, function () {
const actual = DI.getDesignParamTypes(FooVarFunc);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(VarFunc);
});
@decorator()
// @ts-ignore
class FooFunc { constructor(public arg: Func) {} }
it(_`${FooFunc} { constructor(public ${Func}) }`, function () {
const actual = DI.getDesignParamTypes(FooFunc);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Func);
});
@decorator()
// @ts-ignore
class FooArrow { constructor(public arg: Arrow) {} }
it(_`${FooArrow} { constructor(public ${Arrow}) }`, function () {
const actual = DI.getDesignParamTypes(FooArrow);
assertIsMutableArray(actual, 1);
expect(actual[0]).to.equal(Arrow);
});
});
});
});
describe(`getDependencies()`, function () {
let getDesignParamTypes: ReturnType<typeof spy>;
beforeEach(function () {
getDesignParamTypes = spy(DI, 'getDesignParamTypes');
});
afterEach(function () {
getDesignParamTypes.restore();
});
it(`uses getDesignParamTypes() if the static inject property does not exist`, function () {
class Bar {}
@decorator()
class Foo { constructor(bar: Bar) { return; } }
const actual = DI.getDependencies(Foo);
expect(getDesignParamTypes).to.have.been.calledWith(Foo);
expect(actual).to.deep.equal([Bar]);
});
it(`uses getDesignParamTypes() if the static inject property is undefined`, function () {
class Bar {}
@decorator()
class Foo { public static inject; constructor(bar: Bar) { return; } }
const actual = DI.getDependencies(Foo);
expect(getDesignParamTypes).to.have.been.calledWith(Foo);
expect(actual).to.deep.equal([Bar]);
});
it(`throws when inject is not an array`, function () {
class Bar {}
class Foo { public static inject = Bar; }
expect(() => DI.getDependencies(Foo)).to.throw();
expect(getDesignParamTypes).not.to.have.been.called;
});
for (const deps of [
[class Bar {}],
[class Bar {}, class Bar {}],
[undefined],
[null],
[42]
]) {
it(_`returns a copy of the inject array ${deps}`, function () {
class Foo { public static inject = deps.slice(); }
const actual = DI.getDependencies(Foo);
expect(getDesignParamTypes).not.to.have.been.called;
expect(actual).to.deep.equal(deps);
expect(actual).not.to.equal(Foo.inject);
});
}
for (const deps of [
[class Bar {}],
[class Bar {}, class Bar {}],
[undefined],
[null],
[42]
]) {
it(_`traverses the 2-layer prototype chain for inject array ${deps}`, function () {
class Foo { public static inject = deps.slice(); }
class Bar extends Foo { public static inject = deps.slice(); }
const actual = DI.getDependencies(Bar);
expect(getDesignParamTypes).not.to.have.been.called;
expect(actual).to.deep.equal([...deps, ...deps]);
expect(actual).not.to.equal(Foo.inject);
expect(actual).not.to.equal(Bar.inject);
});
it(_`traverses the 3-layer prototype chain for inject array ${deps}`, function () {
class Foo { public static inject = deps.slice(); }
class Bar extends Foo { public static inject = deps.slice(); }
class Baz extends Bar { public static inject = deps.slice(); }
const actual = DI.getDependencies(Baz);
expect(getDesignParamTypes).not.to.have.been.called;
expect(actual).to.deep.equal([...deps, ...deps, ...deps]);
expect(actual).not.to.equal(Foo.inject);
expect(actual).not.to.equal(Bar.inject);
expect(actual).not.to.equal(Baz.inject);
});
it(_`traverses the 1-layer + 2-layer prototype chain (with gap) for inject array ${deps}`, function () {
class Foo { public static inject = deps.slice(); }
class Bar extends Foo { }
class Baz extends Bar { public static inject = deps.slice(); }
class Qux extends Baz { public static inject = deps.slice(); }
const actual = DI.getDependencies(Qux);
expect(getDesignParamTypes).not.to.have.been.called;
expect(actual).to.deep.equal([...deps, ...deps, ...deps]);
expect(actual).not.to.equal(Foo.inject);
expect(actual).not.to.equal(Baz.inject);
expect(actual).not.to.equal(Qux.inject);
});
}
});
describe(`createInterface()`, function () {
it(`returns a function that has withDefault and noDefault functions`, function () {
const sut = DI.createInterface();
expect(typeof sut).to.equal('function');
expect(typeof sut.withDefault).to.equal('function');
expect(typeof sut.noDefault).to.equal('function');
});
it(`noDefault returns self`, function () {
const sut = DI.createInterface();
expect(sut.noDefault()).to.equal(sut);
});
it(`withDefault returns self with modified withDefault that throws`, function () {
const sut = DI.createInterface();
const sut2 = sut.withDefault(null as any);
expect(sut).to.equal(sut2);
expect(() => sut.withDefault(null as any)).to.throw;
});
describe(`withDefault returns self with register function that registers the appropriate resolver`, function () {
let sut: IDefaultableInterfaceSymbol<any>;
let container: IContainer;
let registerResolver: ReturnType<typeof spy>;
beforeEach(function () {
sut = DI.createInterface();
container = new Container();
registerResolver = spy(container, 'registerResolver');
});
afterEach(function () {
registerResolver.restore();
});
function matchResolver(key: any, strategy: any, state: any): SinonMatcher {
return match(val => val.key === key && val.strategy === strategy && val.state === state);
}
it(`instance without key`, function () {
const value = {};
sut.withDefault(builder => builder.instance(value));
(sut as any).register(container);
expect(registerResolver).to.have.been.calledWith(sut, matchResolver(sut, ResolverStrategy.instance, value));
});
it(`instance with key`, function () {
const value = {};
sut.withDefault(builder => builder.instance(value));
(sut as any).register(container, 'key');
expect(registerResolver).to.have.been.calledWith('key', matchResolver('key', ResolverStrategy.instance, value));
});
it(`singleton without key`, function () {
class Foo {}
sut.withDefault(builder => builder.singleton(Foo));
(sut as any).register(container);
expect(registerResolver).to.have.been.calledWith(sut, matchResolver(sut, ResolverStrategy.singleton, Foo));
});
it(`singleton with key`, function () {
class Foo {}
sut.withDefault(builder => builder.singleton(Foo));
(sut as any).register(container, 'key');
expect(registerResolver).to.have.been.calledWith('key', matchResolver('key', ResolverStrategy.singleton, Foo));
});
it(`transient without key`, function () {
class Foo {}
sut.withDefault(builder => builder.transient(Foo));
(sut as any).register(container);
expect(registerResolver).to.have.been.calledWith(sut, matchResolver(sut, ResolverStrategy.transient, Foo));
});
it(`transient with key`, function () {
class Foo {}
sut.withDefault(builder => builder.transient(Foo));
(sut as any).register(container, 'key');
expect(registerResolver).to.have.been.calledWith('key', matchResolver('key', ResolverStrategy.transient, Foo));
});
it(`callback without key`, function () {
const callback = () => { return; };
sut.withDefault(builder => builder.callback(callback));
(sut as any).register(container);
expect(registerResolver).to.have.been.calledWith(sut, matchResolver(sut, ResolverStrategy.callback, callback));
});
it(`callback with key`, function () {
const callback = () => { return; };
sut.withDefault(builder => builder.callback(callback));
(sut as any).register(container, 'key');
expect(registerResolver).to.have.been.calledWith('key', matchResolver('key', ResolverStrategy.callback, callback));
});
it(`aliasTo without key`, function () {
sut.withDefault(builder => builder.aliasTo('key2'));
(sut as any).register(container);
expect(registerResolver).to.have.been.calledWith(sut, matchResolver(sut, ResolverStrategy.alias, 'key2'));
});
it(`aliasTo with key`, function () {
sut.withDefault(builder => builder.aliasTo('key2'));
(sut as any).register(container, 'key1');
expect(registerResolver).to.have.been.calledWith('key1', matchResolver('key1', ResolverStrategy.alias, 'key2'));
});
});
});
});
describe(`The inject decorator`, function () {
class Dep1 {}
class Dep2 {}
class Dep3 {}
it(`can decorate classes with explicit dependencies`, function () {
@inject(Dep1, Dep2, Dep3)
class Foo {}
expect(Foo['inject']).to.deep.equal([Dep1, Dep2, Dep3]);
});
it(`can decorate classes with implicit dependencies`, function () {
@inject()
class Foo { constructor(dep1: Dep1, dep2: Dep2, dep3: Dep3) { return; } }
expect(Foo['inject']).to.deep.equal([Dep1, Dep2, Dep3]);
});
it(`can decorate constructor parameters explicitly`, function () {
class Foo { constructor(@inject(Dep1)dep1, @inject(Dep2)dep2, @inject(Dep3)dep3) { return; } }
expect(Foo['inject']).to.deep.equal([Dep1, Dep2, Dep3]);
});
it(`can decorate constructor parameters implicitly`, function () {
class Foo { constructor(@inject() dep1: Dep1, @inject() dep2: Dep2, @inject() dep3: Dep3) { return; } }
expect(Foo['inject']).to.deep.equal([Dep1, Dep2, Dep3]);
});
it(`can decorate properties explicitly`, function () {
// @ts-ignore
class Foo { @inject(Dep1)public dep1; @inject(Dep2)public dep2; @inject(Dep3)public dep3; }
expect(Foo['inject'].dep1).to.equal(Dep1);
expect(Foo['inject'].dep2).to.equal(Dep2);
expect(Foo['inject'].dep3).to.equal(Dep3);
});
it(`cannot decorate properties implicitly`, function () {
// @ts-ignore
class Foo { @inject()public dep1: Dep1; @inject()public dep2: Dep2; @inject()public dep3: Dep3; }
expect(Foo['inject'].dep1).to.equal(undefined);
expect(Foo['inject'].dep2).to.equal(undefined);
expect(Foo['inject'].dep3).to.equal(undefined);
});
});
describe(`The transient decorator`, function () {
it(`works as a plain decorator`, function () {
@transient
class Foo {}
expect(Foo['register']).to.be.a('function');
const container = DI.createContainer();
const foo1 = container.get(Foo);
const foo2 = container.get(Foo);
expect(foo1).not.to.equal(foo2);
});
it(`works as an invocation`, function () {
@transient()
class Foo {}
expect(Foo['register']).to.be.a('function');
const container = DI.createContainer();
const foo1 = container.get(Foo);
const foo2 = container.get(Foo);
expect(foo1).not.to.equal(foo2);
});
});
describe(`The singleton decorator`, function () {
it(`works as a plain decorator`, function () {
@singleton
class Foo {}
expect(Foo['register']).to.be.a('function');
const container = DI.createContainer();
const foo1 = container.get(Foo);
const foo2 = container.get(Foo);
expect(foo1).to.equal(foo2);
});
it(`works as an invocation`, function () {
@singleton()
class Foo {}
expect(Foo['register']).to.be.a('function');
const container = DI.createContainer();
const foo1 = container.get(Foo);
const foo2 = container.get(Foo);
expect(foo1).to.equal(foo2);
});
});
describe(`The Resolver class`, function () {
let container: IContainer;
let registerResolver: ReturnType<typeof spy>;
beforeEach(function () {
container = new Container();
registerResolver = spy(container, 'registerResolver');
});
afterEach(function () {
registerResolver.restore();
});
describe(`register()`, function () {
it(`registers the resolver to the container with the provided key`, function () {
const sut = new Resolver('foo', 0, null);
sut.register(container, 'bar');
expect(registerResolver).to.have.been.calledWith('bar', sut);
});
it(`registers the resolver to the container with its own`, function () {
const sut = new Resolver('foo', 0, null);
sut.register(container);
expect(registerResolver).to.have.been.calledWith('foo', sut);
});
});
describe(`resolve()`, function () {
it(`instance - returns state`, function () {
const state = {};
const sut = new Resolver('foo', ResolverStrategy.instance, state);
const actual = sut.resolve(container, container);
expect(actual).to.equal(state);
});
it(`singleton - returns an instance of the type and sets strategy to instance`, function () {
class Foo {}
const sut = new Resolver('foo', ResolverStrategy.singleton, Foo);
const actual = sut.resolve(container, container);
expect(actual).to.be.instanceof(Foo);
const actual2 = sut.resolve(container, container);
expect(actual2).to.equal(actual);
});
it(`transient - always returns a new instance of the type`, function () {
class Foo {}
const sut = new Resolver('foo', ResolverStrategy.transient, Foo);
const actual1 = sut.resolve(container, container);
expect(actual1).to.be.instanceof(Foo);
const actual2 = sut.resolve(container, container);
expect(actual2).to.be.instanceof(Foo);
expect(actual2).not.to.equal(actual1);
});
it(`array - calls resolve() on the first item in the state array`, function () {
const resolver = { resolve: spy() };
const sut = new Resolver('foo', ResolverStrategy.array, [resolver]);
sut.resolve(container, container);
expect(resolver.resolve).to.have.been.calledWith(container, container);
});
it(`throws for unknown strategy`, function () {
const sut = new Resolver('foo', -1, null);
expect(() => sut.resolve(container, container)).to.throw(/6/);
});
});
describe(`getFactory()`, function () {
it(`returns a new singleton Factory if it does not exist`, function () {
class Foo {}
const sut = new Resolver(Foo, ResolverStrategy.singleton, Foo);
const actual = sut.getFactory(container);
expect(actual).to.be.instanceof(Factory);
expect(actual.Type).to.equal(Foo);
});
it(`returns a new transient Factory if it does not exist`, function () {
class Foo {}
const sut = new Resolver(Foo, ResolverStrategy.transient, Foo);
const actual = sut.getFactory(container);
expect(actual).to.be.instanceof(Factory);
expect(actual.Type).to.equal(Foo);
});
it(`returns a null for instance strategy`, function () {
class Foo {}
const sut = new Resolver(Foo, ResolverStrategy.instance, Foo);
const actual = sut.getFactory(container);
expect(actual).to.equal(null);
});
it(`returns a null for array strategy`, function () {
class Foo {}
const sut = new Resolver(Foo, ResolverStrategy.array, Foo);
const actual = sut.getFactory(container);
expect(actual).to.equal(null);
});
it(`returns a null for alias strategy`, function () {
class Foo {}
const sut = new Resolver(Foo, ResolverStrategy.alias, Foo);
const actual = sut.getFactory(container);
expect(actual).to.equal(null);
});
it(`returns a null for callback strategy`, function () {
class Foo {}
const sut = new Resolver(Foo, ResolverStrategy.callback, Foo);
const actual = sut.getFactory(container);
expect(actual).to.equal(null);
});
});
});
describe(`The Factory class`, function () {
describe(`create()`, function () {
for (const count of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) {
it(`returns a new Factory with ${count} deps`, function () {
class Bar {}
class Foo {public static inject = Array(count).map(c => Bar); }
const actual = Factory.create(Foo);
expect(actual).to.be.instanceof(Factory);
expect(actual.Type).to.equal(Foo);
if (count < 6) {
expect(actual['invoker']).to.equal(classInvokers[count]);
} else {
expect(actual['invoker']).to.equal(fallbackInvoker);
}
expect(actual['dependencies']).not.to.equal(Foo.inject);
expect(actual['dependencies']).to.deep.equal(Foo.inject);
});
}
});
describe(`construct()`, function () {
for (const staticCount of [0, 1, 2, 3, 4, 5, 6, 7]) {
for (const dynamicCount of [0, 1, 2]) {
const container = new Container();
it(`instantiates a type with ${staticCount} static deps and ${dynamicCount} dynamic deps`, function () {
class Bar {}
class Foo {public static inject = Array(staticCount).fill(Bar); public args: any[]; constructor(...args: any[]) {this.args = args; }}
const sut = Factory.create(Foo);
const dynamicDeps = dynamicCount ? Array(dynamicCount).fill({}) : undefined;
const actual = sut.construct(container, dynamicDeps);
for (let i = 0, ii = Foo.inject.length; i < ii; ++i) {
expect(actual.args[i]).to.be.instanceof(Foo.inject[i]);
}
for (let i = 0, ii = dynamicDeps ? dynamicDeps.length : 0; i < ii; ++i) {
expect(actual.args[Foo.inject.length + i]).to.equal(dynamicDeps[i]);
}
});
}
}
});
describe(`registerTransformer()`, function () {
it(`registers the transformer`, function () {
const container = new Container();
class Foo {public bar; public baz; }
const sut = Factory.create(Foo);
// tslint:disable-next-line:prefer-object-spread
sut.registerTransformer(foo2 => Object.assign(foo2, { bar: 1 }));
// tslint:disable-next-line:prefer-object-spread
sut.registerTransformer(foo2 => Object.assign(foo2, { baz: 2 }));
const foo = sut.construct(container);
expect(foo.bar).to.equal(1);
expect(foo.baz).to.equal(2);
expect(foo).to.be.instanceof(Foo);
});
});
});
describe(`The Container class`, function () {
let sut: IContainer;
beforeEach(function () {
sut = new Container();
});
describe(`register()`, function () {
let register: ReturnType<typeof spy>;
beforeEach(function () {
register = spy();
});
it(_`calls register() on {register}`, function () {
sut.register({register});
expect(register).to.have.been.calledWith(sut);
});
it(_`calls register() on {register},{register}`, function () {
sut.register({register}, {register});
expect(register).to.have.been.calledWith(sut);
expect(register.getCalls().length).to.equal(2);
});
it(_`calls register() on [{register},{register}]`, function () {
sut.register([{register}, {register}] as any);
expect(register).to.have.been.calledWith(sut);
expect(register.getCalls().length).to.equal(2);
});
it(_`calls register() on {foo:{register}}`, function () {
sut.register({foo: {register}});
expect(register).to.have.been.calledWith(sut);
});
it(_`calls register() on {foo:{register}},{foo:{register}}`, function () {
sut.register({foo: {register}}, {foo: {register}});
expect(register).to.have.been.calledWith(sut);
expect(register.getCalls().length).to.equal(2);
});
it(_`calls register() on [{foo:{register}},{foo:{register}}]`, function () {
sut.register([{foo: {register}}, {foo: {register}}] as any);
expect(register).to.have.been.calledWith(sut);
expect(register.getCalls().length).to.equal(2);
});
it(_`calls register() on {register},{foo:{register}}`, function () {
sut.register({register}, {foo: {register}});
expect(register).to.have.been.calledWith(sut);
expect(register.getCalls().length).to.equal(2);
});
it(_`calls register() on [{register},{foo:{register}}]`, function () {
sut.register([{register}, {foo: {register}}] as any);
expect(register).to.have.been.calledWith(sut);
expect(register.getCalls().length).to.equal(2);
});
it(_`calls register() on [{register},{}]`, function () {
sut.register([{register}, {}] as any);
expect(register).to.have.been.calledWith(sut);
});
it(_`calls register() on [{},{register}]`, function () {
sut.register([{}, {register}] as any);
expect(register).to.have.been.calledWith(sut);
});
it(_`calls register() on [{foo:{register}},{foo:{}}]`, function () {
sut.register([{foo: {register}}, {foo: {}}] as any);
expect(register).to.have.been.calledWith(sut);
});
it(_`calls register() on [{foo:{}},{foo:{register}}]`, function () {
sut.register([{foo: {}}, {foo: {register}}] as any);
expect(register).to.have.been.calledWith(sut);
});
});
describe(`registerResolver()`, function () {
for (const key of [null, undefined, Object]) {
it(_`throws on invalid key ${key}`, function () {
expect(() => sut.registerResolver(key, null as any)).to.throw(/5/);
});
}
it(`registers the resolver if it does not exist yet`, function () {
const key = {};
const resolver = new Resolver(key, ResolverStrategy.instance, {});
sut.registerResolver(key, resolver);
const actual = sut.getResolver(key);
expect(actual).to.equal(resolver);
});
it(`changes to array resolver if the key already exists`, function () {
const key = {};
const resolver1 = new Resolver(key, ResolverStrategy.instance, {});
const resolver2 = new Resolver(key, ResolverStrategy.instance, {});
sut.registerResolver(key, resolver1);
const actual1 = sut.getResolver(key);
expect(actual1).to.equal(resolver1);
sut.registerResolver(key, resolver2);
const actual2 = sut.getResolver(key);
expect(actual2).not.to.equal(actual1);
expect(actual2).not.to.equal(resolver1);
expect(actual2).not.to.equal(resolver2);
expect(actual2['strategy']).to.equal(ResolverStrategy.array);
expect(actual2['state'][0]).to.equal(resolver1);
expect(actual2['state'][1]).to.equal(resolver2);
});
it(`appends to the array resolver if the key already exists more than once`, function () {
const key = {};
const resolver1 = new Resolver(key, ResolverStrategy.instance, {});
const resolver2 = new Resolver(key, ResolverStrategy.instance, {});
const resolver3 = new Resolver(key, ResolverStrategy.instance, {});
sut.registerResolver(key, resolver1);
sut.registerResolver(key, resolver2);
sut.registerResolver(key, resolver3);
const actual1 = sut.getResolver(key);
expect(actual1['strategy']).to.equal(ResolverStrategy.array);
expect(actual1['state'][0]).to.equal(resolver1);
expect(actual1['state'][1]).to.equal(resolver2);
expect(actual1['state'][2]).to.equal(resolver3);
});
});
describe(`registerTransformer()`, function () {
for (const key of [null, undefined, Object]) {
it(_`throws on invalid key ${key}`, function () {
expect(() => sut.registerTransformer(key, null as any)).to.throw(/5/);
});
}
it(`registers the transformer if it does not exist yet`, function () {
});
it(`reuses the existing transformer if it exists`, function () {
});
});
describe(`getResolver()`, function () {
for (const key of [null, undefined, Object]) {
it(_`throws on invalid key ${key}`, function () {
expect(() => sut.getResolver(key, null as any)).to.throw(/5/);
});
}
});
describe(`has()`, function () {
for (const key of [null, undefined, Object]) {
it(_`returns false for non-existing key ${key}`, function () {
expect(sut.has(key as any, false)).to.equal(false);
});
}
it(`returns true for existing key`, function () {
const key = {};
sut.registerResolver(key, new Resolver(key, ResolverStrategy.instance, {}));
expect(sut.has(key as any, false)).to.equal(true);
});