-
Notifications
You must be signed in to change notification settings - Fork 24.8k
/
di_spec.ts
3588 lines (3039 loc) Β· 124 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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule} from '@angular/common';
import {Attribute, ChangeDetectorRef, Component, ComponentFactoryResolver, ComponentRef, Directive, ElementRef, EventEmitter, forwardRef, Host, HostBinding, Inject, Injectable, InjectFlags, InjectionToken, INJECTOR, Injector, Input, LOCALE_ID, NgModule, NgZone, Optional, Output, Pipe, PipeTransform, Self, SkipSelf, TemplateRef, ViewChild, ViewContainerRef, ViewRef, Ι΅DEFAULT_LOCALE_ID as DEFAULT_LOCALE_ID} from '@angular/core';
import {Ι΅INJECTOR_SCOPE} from '@angular/core/src/core';
import {ViewRef as ViewRefInternal} from '@angular/core/src/render3/view_ref';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {ivyEnabled, onlyInIvy} from '@angular/private/testing';
import {BehaviorSubject} from 'rxjs';
describe('di', () => {
describe('no dependencies', () => {
it('should create directive with no deps', () => {
@Directive({selector: '[dir]', exportAs: 'dir'})
class MyDirective {
value = 'Created';
}
@Component({template: '<div dir #dir="dir">{{ dir.value }}</div>'})
class MyComp {
}
TestBed.configureTestingModule({declarations: [MyDirective, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toContain('Created');
});
});
describe('multi providers', () => {
it('should process ModuleWithProvider providers after module imports', () => {
const testToken = new InjectionToken<string[]>('test-multi');
@NgModule({providers: [{provide: testToken, useValue: 'A', multi: true}]})
class TestModuleA {
}
@NgModule({providers: [{provide: testToken, useValue: 'B', multi: true}]})
class TestModuleB {
}
TestBed.configureTestingModule({
imports: [
{
ngModule: TestModuleA,
providers: [{provide: testToken, useValue: 'C', multi: true}],
},
TestModuleB,
]
});
expect(TestBed.inject(testToken)).toEqual(['A', 'B', 'C']);
});
});
describe('directive injection', () => {
let log: string[] = [];
@Directive({selector: '[dirB]', exportAs: 'dirB'})
class DirectiveB {
@Input() value = 'DirB';
constructor() {
log.push(this.value);
}
}
beforeEach(() => log = []);
it('should create directive with intra view dependencies', () => {
@Directive({selector: '[dirA]', exportAs: 'dirA'})
class DirectiveA {
value = 'DirA';
}
@Directive({selector: '[dirC]', exportAs: 'dirC'})
class DirectiveC {
value: string;
constructor(dirA: DirectiveA, dirB: DirectiveB) {
this.value = dirA.value + dirB.value;
}
}
@Component({
template: `
<div dirA>
<span dirB dirC #dir="dirC">{{ dir.value }}</span>
</div>
`
})
class MyComp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, DirectiveC, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('span');
expect(divElement.textContent).toContain('DirADirB');
});
it('should instantiate injected directives in dependency order', () => {
@Directive({selector: '[dirA]'})
class DirectiveA {
value = 'dirA';
constructor(dirB: DirectiveB) {
log.push(`DirA (dep: ${dirB.value})`);
}
}
@Component({template: '<div dirA dirB></div>'})
class MyComp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'DirA (dep: DirB)']);
});
it('should fallback to the module injector', () => {
@Directive({selector: '[dirA]'})
class DirectiveA {
value = 'dirA';
constructor(dirB: DirectiveB) {
log.push(`DirA (dep: ${dirB.value})`);
}
}
// - dirB is know to the node injectors
// - then when dirA tries to inject dirB, it will check the node injector first tree
// - if not found, it will check the module injector tree
@Component({template: '<div dirB></div><div dirA></div>'})
class MyComp {
}
TestBed.configureTestingModule({
declarations: [DirectiveA, DirectiveB, MyComp],
providers: [{provide: DirectiveB, useValue: {value: 'module'}}]
});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'DirA (dep: module)']);
});
it('should instantiate injected directives before components', () => {
@Component({selector: 'my-comp', template: ''})
class MyComp {
constructor(dirB: DirectiveB) {
log.push(`Comp (dep: ${dirB.value})`);
}
}
@Component({template: '<my-comp dirB></my-comp>'})
class MyApp {
}
TestBed.configureTestingModule({declarations: [DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'Comp (dep: DirB)']);
});
it('should inject directives in the correct order in a for loop', () => {
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(dir: DirectiveB) {
log.push(`DirA (dep: ${dir.value})`);
}
}
@Component({template: '<div dirA dirB *ngFor="let i of array"></div>'})
class MyComp {
array = [1, 2, 3];
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(log).toEqual(
['DirB', 'DirA (dep: DirB)', 'DirB', 'DirA (dep: DirB)', 'DirB', 'DirA (dep: DirB)']);
});
it('should instantiate directives with multiple out-of-order dependencies', () => {
@Directive({selector: '[dirA]'})
class DirectiveA {
value = 'DirA';
constructor() {
log.push(this.value);
}
}
@Directive({selector: '[dirC]'})
class DirectiveC {
value = 'DirC';
constructor() {
log.push(this.value);
}
}
@Directive({selector: '[dirB]'})
class DirectiveB {
constructor(dirA: DirectiveA, dirC: DirectiveC) {
log.push(`DirB (deps: ${dirA.value} and ${dirC.value})`);
}
}
@Component({template: '<div dirA dirB dirC></div>'})
class MyComp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, DirectiveC, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(log).toEqual(['DirA', 'DirC', 'DirB (deps: DirA and DirC)']);
});
it('should instantiate in the correct order for complex case', () => {
@Directive({selector: '[dirC]'})
class DirectiveC {
value = 'DirC';
constructor(dirB: DirectiveB) {
log.push(`DirC (dep: ${dirB.value})`);
}
}
@Directive({selector: '[dirA]'})
class DirectiveA {
value = 'DirA';
constructor(dirC: DirectiveC) {
log.push(`DirA (dep: ${dirC.value})`);
}
}
@Directive({selector: '[dirD]'})
class DirectiveD {
value = 'DirD';
constructor(dirA: DirectiveA) {
log.push(`DirD (dep: ${dirA.value})`);
}
}
@Component({selector: 'my-comp', template: ''})
class MyComp {
constructor(dirD: DirectiveD) {
log.push(`Comp (dep: ${dirD.value})`);
}
}
@Component({template: '<my-comp dirA dirB dirC dirD></my-comp>'})
class MyApp {
}
TestBed.configureTestingModule(
{declarations: [DirectiveA, DirectiveB, DirectiveC, DirectiveD, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(log).toEqual(
['DirB', 'DirC (dep: DirB)', 'DirA (dep: DirC)', 'DirD (dep: DirA)', 'Comp (dep: DirD)']);
});
it('should instantiate in correct order with mixed parent and peer dependencies', () => {
@Component({template: '<div dirA dirB dirC></div>'})
class MyApp {
value = 'App';
}
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(dirB: DirectiveB, app: MyApp) {
log.push(`DirA (deps: ${dirB.value} and ${app.value})`);
}
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'DirA (deps: DirB and App)']);
});
it('should not use a parent when peer dep is available', () => {
let count = 1;
@Directive({selector: '[dirB]'})
class DirectiveB {
count: number;
constructor() {
log.push(`DirB`);
this.count = count++;
}
}
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(dirB: DirectiveB) {
log.push(`DirA (dep: DirB - ${dirB.count})`);
}
}
@Component({selector: 'my-comp', template: '<div dirA dirB></div>'})
class MyComp {
}
@Component({template: '<my-comp dirB></my-comp>'})
class MyApp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
expect(log).toEqual(['DirB', 'DirB', 'DirA (dep: DirB - 2)']);
});
describe('dependencies in parent views', () => {
@Directive({selector: '[dirA]', exportAs: 'dirA'})
class DirectiveA {
injector: Injector;
constructor(public dirB: DirectiveB, public vcr: ViewContainerRef) {
this.injector = vcr.injector;
}
}
@Component(
{selector: 'my-comp', template: '<div dirA #dir="dirA">{{ dir.dirB.value }}</div>'})
class MyComp {
}
it('should find dependencies on component hosts', () => {
@Component({template: '<my-comp dirB></my-comp>'})
class MyApp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirB');
});
it('should find dependencies for directives in embedded views', () => {
@Component({
template: `<div dirB>
<div *ngIf="showing">
<div dirA #dir="dirA">{{ dir.dirB.value }}</div>
</div>
</div>`
})
class MyApp {
showing = false;
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.componentInstance.showing = true;
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirB');
});
it('should find dependencies of directives nested deeply in inline views', () => {
@Component({
template: `<div dirB>
<ng-container *ngIf="!skipContent">
<ng-container *ngIf="!skipContent2">
<div dirA #dir="dirA">{{ dir.dirB.value }}</div>
</ng-container>
</ng-container>
</div>`
})
class MyApp {
skipContent = false;
skipContent2 = false;
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirB');
});
it('should find dependencies in declaration tree of ng-template (not insertion tree)', () => {
@Directive({selector: '[structuralDir]'})
class StructuralDirective {
@Input() tmp!: TemplateRef<any>;
constructor(public vcr: ViewContainerRef) {}
create() {
this.vcr.createEmbeddedView(this.tmp);
}
}
@Component({
template: `<div dirB value="declaration">
<ng-template #foo>
<div dirA #dir="dirA">{{ dir.dirB.value }}</div>
</ng-template>
</div>
<div dirB value="insertion">
<div structuralDir [tmp]="foo"></div>
<!-- insertion point -->
</div>`
})
class MyComp {
@ViewChild(StructuralDirective) structuralDir!: StructuralDirective;
}
TestBed.configureTestingModule(
{declarations: [StructuralDirective, DirectiveA, DirectiveB, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
fixture.componentInstance.structuralDir.create();
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div[value=insertion]');
expect(divElement.textContent).toEqual('declaration');
});
it('should create injectors on second template pass', () => {
@Component({
template: `<div>
<my-comp dirB></my-comp>
<my-comp dirB></my-comp>
</div>`
})
class MyApp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirBDirB');
});
it('should create injectors and host bindings in same view', () => {
@Directive({selector: '[hostBindingDir]'})
class HostBindingDirective {
@HostBinding('id') id = 'foo';
}
@Component({
template: `<div dirB hostBindingDir>
<p dirA #dir="dirA">{{ dir.dirB.value }}</p>
</div>`
})
class MyApp {
@ViewChild(HostBindingDirective) hostBindingDir!: HostBindingDirective;
@ViewChild(DirectiveA) dirA!: DirectiveA;
}
TestBed.configureTestingModule(
{declarations: [DirectiveA, DirectiveB, HostBindingDirective, MyApp]});
const fixture = TestBed.createComponent(MyApp);
fixture.detectChanges();
const divElement = fixture.nativeElement.querySelector('div');
expect(divElement.textContent).toEqual('DirB');
expect(divElement.id).toEqual('foo');
const dirA = fixture.componentInstance.dirA;
expect(dirA.vcr.injector).toEqual(dirA.injector);
const hostBindingDir = fixture.componentInstance.hostBindingDir;
hostBindingDir.id = 'bar';
fixture.detectChanges();
expect(divElement.id).toBe('bar');
});
it('dynamic components should find dependencies when parent is projected', () => {
@Directive({selector: '[dirA]'})
class DirA {
}
@Directive({selector: '[dirB]'})
class DirB {
}
@Component({selector: 'child', template: ''})
class Child {
constructor(@Optional() readonly dirA: DirA, @Optional() readonly dirB: DirB) {}
}
@Component({
selector: 'projector',
template: '<ng-content></ng-content>',
})
class Projector {
}
@Component({
template: `
<projector>
<div dirA>
<ng-container #childOrigin></ng-container>
<ng-container #childOriginWithDirB dirB></ng-container>
</div>
</projector>`,
entryComponents: [Child]
})
class MyApp {
@ViewChild('childOrigin', {read: ViewContainerRef, static: true})
childOrigin!: ViewContainerRef;
@ViewChild('childOriginWithDirB', {read: ViewContainerRef, static: true})
childOriginWithDirB!: ViewContainerRef;
childFactory = this.resolver.resolveComponentFactory(Child);
constructor(readonly resolver: ComponentFactoryResolver, readonly injector: Injector) {}
addChild() {
return this.childOrigin.createComponent(this.childFactory);
}
addChildWithDirB() {
return this.childOriginWithDirB.createComponent(this.childFactory);
}
}
const fixture =
TestBed.configureTestingModule({declarations: [Child, DirA, DirB, Projector, MyApp]})
.createComponent(MyApp);
const child = fixture.componentInstance.addChild();
expect(child).toBeDefined();
expect(child.instance.dirA)
.not.toBeNull('dirA should be found. It is on the parent of the viewContainerRef.');
const child2 = fixture.componentInstance.addChildWithDirB();
expect(child2).toBeDefined();
expect(child2.instance.dirA)
.not.toBeNull('dirA should be found. It is on the parent of the viewContainerRef.');
expect(child2.instance.dirB)
.toBeNull(
'dirB appears on the ng-container and should not be found because the ' +
'viewContainerRef.createComponent node is inserted next to the container.');
});
});
it('should throw if directive is not found anywhere', () => {
@Directive({selector: '[dirB]'})
class DirectiveB {
constructor() {}
}
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(siblingDir: DirectiveB) {}
}
@Component({template: '<div dirA></div>'})
class MyComp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(/No provider for DirectiveB/);
});
it('should throw if directive is not found in ancestor tree', () => {
@Directive({selector: '[dirB]'})
class DirectiveB {
constructor() {}
}
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(siblingDir: DirectiveB) {}
}
@Component({template: '<div dirA></div><div dirB></div>'})
class MyComp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
expect(() => TestBed.createComponent(MyComp)).toThrowError(/No provider for DirectiveB/);
});
onlyInIvy('Ivy has different error message for circular dependency')
.it('should throw if directives try to inject each other', () => {
@Directive({selector: '[dirB]'})
class DirectiveB {
constructor(@Inject(forwardRef(() => DirectiveA)) siblingDir: DirectiveA) {}
}
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(siblingDir: DirectiveB) {}
}
@Component({template: '<div dirA dirB></div>'})
class MyComp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
expect(() => TestBed.createComponent(MyComp))
.toThrowError(
'NG0200: Circular dependency in DI detected for DirectiveA. Find more at https://angular.io/errors/NG0200');
});
onlyInIvy('Ivy has different error message for circular dependency')
.it('should throw if directive tries to inject itself', () => {
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(siblingDir: DirectiveA) {}
}
@Component({template: '<div dirA></div>'})
class MyComp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
expect(() => TestBed.createComponent(MyComp))
.toThrowError(
'NG0200: Circular dependency in DI detected for DirectiveA. Find more at https://angular.io/errors/NG0200');
});
describe('flags', () => {
@Directive({selector: '[dirB]'})
class DirectiveB {
@Input('dirB') value = '';
}
describe('Optional', () => {
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(@Optional() public dirB: DirectiveB) {}
}
it('should not throw if dependency is @Optional (module injector)', () => {
@Component({template: '<div dirA></div>'})
class MyComp {
@ViewChild(DirectiveA) dirA!: DirectiveA;
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dirA = fixture.componentInstance.dirA;
expect(dirA.dirB).toBeNull();
});
it('should return null if @Optional dependency has @Self flag', () => {
@Directive({selector: '[dirC]'})
class DirectiveC {
constructor(@Optional() @Self() public dirB: DirectiveB) {}
}
@Component({template: '<div dirC></div>'})
class MyComp {
@ViewChild(DirectiveC) dirC!: DirectiveC;
}
TestBed.configureTestingModule({declarations: [DirectiveC, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dirC = fixture.componentInstance.dirC;
expect(dirC.dirB).toBeNull();
});
it('should not throw if dependency is @Optional but defined elsewhere', () => {
@Directive({selector: '[dirC]'})
class DirectiveC {
constructor(@Optional() public dirB: DirectiveB) {}
}
@Component({template: '<div dirB></div><div dirC></div>'})
class MyComp {
@ViewChild(DirectiveC) dirC!: DirectiveC;
}
TestBed.configureTestingModule({declarations: [DirectiveB, DirectiveC, MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const dirC = fixture.componentInstance.dirC;
expect(dirC.dirB).toBeNull();
});
});
onlyInIvy('Ivy has different error message when dependency is not found')
.it('should check only the current node with @Self', () => {
@Directive({selector: '[dirA]'})
class DirectiveA {
constructor(@Self() public dirB: DirectiveB) {}
}
@Component({template: '<div dirB><div dirA></div></div>'})
class MyComp {
}
TestBed.configureTestingModule({declarations: [DirectiveA, DirectiveB, MyComp]});
expect(() => TestBed.createComponent(MyComp))
.toThrowError(/NG0201: No provider for DirectiveB found in NodeInjector/);
});
describe('SkipSelf', () => {
describe('Injectors', () => {
it('should support @SkipSelf when injecting Injectors', () => {
@Component({
selector: 'parent',
template: '<child></child>',
providers: [{
provide: 'token',
useValue: 'PARENT',
}]
})
class ParentComponent {
}
@Component({
selector: 'child',
template: '...',
providers: [{
provide: 'token',
useValue: 'CHILD',
}]
})
class ChildComponent {
constructor(public injector: Injector, @SkipSelf() public parentInjector: Injector) {}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
const childComponent =
fixture.debugElement.query(By.directive(ChildComponent)).componentInstance;
expect(childComponent.injector.get('token')).toBe('CHILD');
expect(childComponent.parentInjector.get('token')).toBe('PARENT');
});
it('should lookup module injector in case @SkipSelf is used and no suitable Injector found in element injector tree',
() => {
let componentInjector: Injector;
let moduleInjector: Injector;
@Component({
selector: 'child',
template: '...',
providers: [{
provide: 'token',
useValue: 'CHILD',
}]
})
class MyComponent {
constructor(@SkipSelf() public injector: Injector) {
componentInjector = injector;
}
}
@NgModule({
declarations: [MyComponent],
providers: [{
provide: 'token',
useValue: 'NG_MODULE',
}]
})
class MyModule {
constructor(public injector: Injector) {
moduleInjector = injector;
}
}
TestBed.configureTestingModule({
imports: [MyModule],
});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect(componentInjector!.get('token')).toBe('NG_MODULE');
expect(moduleInjector!.get('token')).toBe('NG_MODULE');
});
it('should respect @Host in case @SkipSelf is used and no suitable Injector found in element injector tree',
() => {
let componentInjector: Injector;
let moduleInjector: Injector;
@Component({
selector: 'child',
template: '...',
providers: [{
provide: 'token',
useValue: 'CHILD',
}]
})
class MyComponent {
constructor(@Host() @SkipSelf() public injector: Injector) {
componentInjector = injector;
}
}
@NgModule({
declarations: [MyComponent],
providers: [{
provide: 'token',
useValue: 'NG_MODULE',
}]
})
class MyModule {
constructor(public injector: Injector) {
moduleInjector = injector;
}
}
TestBed.configureTestingModule({
imports: [MyModule],
});
// If a token is injected with the @Host flag, the module injector is not searched
// for that token in Ivy.
if (ivyEnabled) {
expect(() => TestBed.createComponent(MyComponent))
.toThrowError(/NG0201: No provider for Injector found in NodeInjector/);
} else {
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect(componentInjector!.get('token')).toBe('NG_MODULE');
expect(moduleInjector!.get('token')).toBe('NG_MODULE');
}
});
it('should throw when injecting Injectors using @SkipSelf and @Host and no Injectors are available in a current view',
() => {
@Component({
selector: 'parent',
template: '<child></child>',
providers: [{
provide: 'token',
useValue: 'PARENT',
}]
})
class ParentComponent {
}
@Component({
selector: 'child',
template: '...',
providers: [{
provide: 'token',
useValue: 'CHILD',
}]
})
class ChildComponent {
constructor(@Host() @SkipSelf() public injector: Injector) {}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
// Ivy has different error message when dependency is not found
const expectedErrorMessage = ivyEnabled ?
/NG0201: No provider for Injector found in NodeInjector/ :
/No provider for Injector/;
expect(() => TestBed.createComponent(ParentComponent))
.toThrowError(expectedErrorMessage);
});
it('should not throw when injecting Injectors using @SkipSelf, @Host, and @Optional and no Injectors are available in a current view',
() => {
@Component({
selector: 'parent',
template: '<child></child>',
providers: [{
provide: 'token',
useValue: 'PARENT',
}]
})
class ParentComponent {
}
@Component({
selector: 'child',
template: '...',
providers: [{
provide: 'token',
useValue: 'CHILD',
}]
})
class ChildComponent {
constructor(@Host() @SkipSelf() @Optional() public injector: Injector) {}
}
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
});
// Ivy has different error message when dependency is not found
const expectedErrorMessage = ivyEnabled ?
/NG0201: No provider for Injector found in NodeInjector/ :
/No provider for Injector/;
expect(() => TestBed.createComponent(ParentComponent))
.not.toThrowError(expectedErrorMessage);
});
});
describe('ElementRef', () => {
// While tokens like `ElementRef` make sense only in a context of a NodeInjector,
// ViewEngine also used `ModuleInjector` tree to lookup such tokens. In Ivy we replicate
// this behavior for now to avoid breaking changes.
it('should lookup module injector in case @SkipSelf is used for `ElementRef` token and Component has no parent',
() => {
let componentElement: ElementRef;
let moduleElement: ElementRef;
@Component({template: '<div>component</div>'})
class MyComponent {
constructor(@SkipSelf() public el: ElementRef) {
componentElement = el;
}
}
@NgModule({
declarations: [MyComponent],
providers: [{
provide: ElementRef,
useValue: {from: 'NG_MODULE'},
}]
})
class MyModule {
constructor(public el: ElementRef) {
moduleElement = el;
}
}
TestBed.configureTestingModule({
imports: [MyModule],
});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect((moduleElement! as any).from).toBe('NG_MODULE');
expect((componentElement! as any).from).toBe('NG_MODULE');
});
it('should return host node when @SkipSelf is used for `ElementRef` token and Component has no parent node',
() => {
let parentElement: ElementRef;
let componentElement: ElementRef;
@Component({selector: 'child', template: '...'})
class MyComponent {
constructor(@SkipSelf() public el: ElementRef) {
componentElement = el;
}
}
@Component({
template: '<child></child>',
})
class ParentComponent {
constructor(public el: ElementRef) {
parentElement = el;
}
}
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [ParentComponent, MyComponent],
});
const fixture = TestBed.createComponent(ParentComponent);
fixture.detectChanges();
expect(componentElement!).toEqual(parentElement!);
});
it('should @SkipSelf on child directive node when injecting ElementRef on nested parent directive',
() => {
let parentRef: ElementRef;
let childRef: ElementRef;
@Directive({selector: '[parent]'})
class ParentDirective {
constructor(elementRef: ElementRef) {
parentRef = elementRef;