/
test_bed_spec.ts
1293 lines (1087 loc) · 43.3 KB
/
test_bed_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 {APP_INITIALIZER, ChangeDetectorRef, Compiler, Component, Directive, ErrorHandler, Inject, Injectable, InjectionToken, Injector, Input, LOCALE_ID, ModuleWithProviders, NgModule, Optional, Pipe, Type, ViewChild, ɵsetClassMetadata as setClassMetadata, ɵɵdefineComponent as defineComponent, ɵɵdefineInjector as defineInjector, ɵɵdefineNgModule as defineNgModule, ɵɵsetNgModuleScope as setNgModuleScope, ɵɵtext as text} from '@angular/core';
import {getTestBed, TestBed} from '@angular/core/testing/src/test_bed';
import {By} from '@angular/platform-browser';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {onlyInIvy} from '@angular/private/testing';
const NAME = new InjectionToken<string>('name');
@Injectable({providedIn: 'root'})
class SimpleService {
static ngOnDestroyCalls: number = 0;
id: number = 1;
ngOnDestroy() {
SimpleService.ngOnDestroyCalls++;
}
}
// -- module: HWModule
@Component({
selector: 'hello-world',
template: '<greeting-cmp></greeting-cmp>',
})
export class HelloWorld {
}
// -- module: Greeting
@Component({
selector: 'greeting-cmp',
template: 'Hello {{ name }}',
})
export class GreetingCmp {
name: string;
constructor(
@Inject(NAME) @Optional() name: string,
@Inject(SimpleService) @Optional() service: SimpleService) {
this.name = name || 'nobody!';
}
}
@Component({
selector: 'cmp-with-providers',
template: '<hello-world></hello-world>',
providers: [
SimpleService, //
{provide: NAME, useValue: `from Component`}
]
})
class CmpWithProviders {
}
@NgModule({
declarations: [GreetingCmp],
exports: [GreetingCmp],
})
export class GreetingModule {
}
@Component({selector: 'simple-cmp', template: '<b>simple</b>'})
export class SimpleCmp {
}
@Component({selector: 'with-refs-cmp', template: '<div #firstDiv></div>'})
export class WithRefsCmp {
}
@Component({selector: 'inherited-cmp', template: 'inherited'})
export class InheritedCmp extends SimpleCmp {
}
@Directive({selector: '[hostBindingDir]', host: {'[id]': 'id'}})
export class HostBindingDir {
id = 'one';
}
@Component({
selector: 'component-with-prop-bindings',
template: `
<div hostBindingDir [title]="title" [attr.aria-label]="label"></div>
<p title="( {{ label }} - {{ title }} )" [attr.aria-label]="label" id="[ {{ label }} ] [ {{ title }} ]">
</p>
`
})
export class ComponentWithPropBindings {
title = 'some title';
label = 'some label';
}
@Component({
selector: 'simple-app',
template: `
<simple-cmp></simple-cmp> - <inherited-cmp></inherited-cmp>
`
})
export class SimpleApp {
}
@Component({selector: 'inline-template', template: '<p>Hello</p>'})
export class ComponentWithInlineTemplate {
}
@NgModule({
declarations: [
HelloWorld, SimpleCmp, WithRefsCmp, InheritedCmp, SimpleApp, ComponentWithPropBindings,
HostBindingDir, CmpWithProviders
],
imports: [GreetingModule],
providers: [
{provide: NAME, useValue: 'World!'},
]
})
export class HelloWorldModule {
}
describe('TestBed', () => {
beforeEach(() => {
getTestBed().resetTestingModule();
TestBed.configureTestingModule({imports: [HelloWorldModule]});
});
it('should compile and render a component', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello World!');
});
it('should give access to the component instance', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.componentInstance).toBeAnInstanceOf(HelloWorld);
});
it('should give the ability to query by css', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
const greetingByCss = hello.debugElement.query(By.css('greeting-cmp'));
expect(greetingByCss.nativeElement).toHaveText('Hello World!');
expect(greetingByCss.componentInstance).toBeAnInstanceOf(GreetingCmp);
});
it('should give the ability to trigger the change detection', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
const greetingByCss = hello.debugElement.query(By.css('greeting-cmp'));
expect(greetingByCss.nativeElement).toHaveText('Hello World!');
greetingByCss.componentInstance.name = 'TestBed!';
hello.detectChanges();
expect(greetingByCss.nativeElement).toHaveText('Hello TestBed!');
});
it('should give the ability to access property bindings on a node', () => {
const fixture = TestBed.createComponent(ComponentWithPropBindings);
fixture.detectChanges();
const divElement = fixture.debugElement.query(By.css('div'));
expect(divElement.properties.id).toEqual('one');
expect(divElement.properties.title).toEqual('some title');
});
it('should give the ability to access interpolated properties on a node', () => {
const fixture = TestBed.createComponent(ComponentWithPropBindings);
fixture.detectChanges();
const paragraphEl = fixture.debugElement.query(By.css('p'));
expect(paragraphEl.properties.title).toEqual('( some label - some title )');
expect(paragraphEl.properties.id).toEqual('[ some label ] [ some title ]');
});
it('should give access to the node injector', () => {
const fixture = TestBed.createComponent(HelloWorld);
fixture.detectChanges();
const injector = fixture.debugElement.query(By.css('greeting-cmp')).injector;
// from the node injector
const greetingCmp = injector.get(GreetingCmp);
expect(greetingCmp.constructor).toBe(GreetingCmp);
// from the node injector (inherited from a parent node)
const helloWorldCmp = injector.get(HelloWorld);
expect(fixture.componentInstance).toBe(helloWorldCmp);
const nameInjected = injector.get(NAME);
expect(nameInjected).toEqual('World!');
});
it('should give access to the node injector for root node', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
const injector = hello.debugElement.injector;
// from the node injector
const helloInjected = injector.get(HelloWorld);
expect(helloInjected).toBe(hello.componentInstance);
// from the module injector
const nameInjected = injector.get(NAME);
expect(nameInjected).toEqual('World!');
});
it('should give access to local refs on a node', () => {
const withRefsCmp = TestBed.createComponent(WithRefsCmp);
const firstDivDebugEl = withRefsCmp.debugElement.query(By.css('div'));
// assert that a native element is referenced by a local ref
expect(firstDivDebugEl.references.firstDiv.tagName.toLowerCase()).toBe('div');
});
it('should give the ability to query by directive', () => {
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
const greetingByDirective = hello.debugElement.query(By.directive(GreetingCmp));
expect(greetingByDirective.componentInstance).toBeAnInstanceOf(GreetingCmp);
});
it('allow to override a template', () => {
// use original template when there is no override
let hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello World!');
// override the template
getTestBed().resetTestingModule();
TestBed.configureTestingModule({imports: [HelloWorldModule]});
TestBed.overrideComponent(GreetingCmp, {set: {template: `Bonjour {{ name }}`}});
hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Bonjour World!');
// restore the original template by calling `.resetTestingModule()`
getTestBed().resetTestingModule();
TestBed.configureTestingModule({imports: [HelloWorldModule]});
hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello World!');
});
it('should run `APP_INITIALIZER` before accessing `LOCALE_ID` provider', () => {
let locale: string = '';
@NgModule({
providers: [
{provide: APP_INITIALIZER, useValue: () => locale = 'fr-FR', multi: true},
{provide: LOCALE_ID, useFactory: () => locale}
]
})
class TestModule {
}
TestBed.configureTestingModule({imports: [TestModule]});
expect(TestBed.inject(LOCALE_ID)).toBe('fr-FR');
});
it('allow to override a provider', () => {
TestBed.overrideProvider(NAME, {useValue: 'injected World!'});
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello injected World!');
});
it('uses the most recent provider override', () => {
TestBed.overrideProvider(NAME, {useValue: 'injected World!'});
TestBed.overrideProvider(NAME, {useValue: 'injected World a second time!'});
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello injected World a second time!');
});
it('overrides a providers in an array', () => {
TestBed.configureTestingModule({
imports: [HelloWorldModule],
providers: [
[{provide: NAME, useValue: 'injected World!'}],
]
});
TestBed.overrideProvider(NAME, {useValue: 'injected World a second time!'});
const hello = TestBed.createComponent(HelloWorld);
hello.detectChanges();
expect(hello.nativeElement).toHaveText('Hello injected World a second time!');
});
it('should not call ngOnDestroy for a service that was overridden', () => {
SimpleService.ngOnDestroyCalls = 0;
TestBed.overrideProvider(SimpleService, {useValue: {id: 2, ngOnDestroy: () => {}}});
const fixture = TestBed.createComponent(CmpWithProviders);
fixture.detectChanges();
const service = TestBed.inject(SimpleService);
expect(service.id).toBe(2);
fixture.destroy();
// verify that original `ngOnDestroy` was not called
expect(SimpleService.ngOnDestroyCalls).toBe(0);
});
describe('module overrides using TestBed.overrideModule', () => {
@Component({
selector: 'test-cmp',
template: '...',
})
class TestComponent {
testField = 'default';
}
@NgModule({
declarations: [TestComponent],
exports: [TestComponent],
})
class TestModule {
}
@Component({
selector: 'app-root',
template: `<test-cmp #testCmpCtrl></test-cmp>`,
})
class AppComponent {
@ViewChild('testCmpCtrl', {static: true}) testCmpCtrl!: TestComponent;
}
@NgModule({
declarations: [AppComponent],
imports: [TestModule],
})
class AppModule {
}
@Component({
selector: 'test-cmp',
template: '...',
})
class MockTestComponent {
testField = 'overwritten';
}
it('should allow declarations override', () => {
TestBed.configureTestingModule({
imports: [AppModule],
});
// replace TestComponent with MockTestComponent
TestBed.overrideModule(TestModule, {
remove: {declarations: [TestComponent], exports: [TestComponent]},
add: {declarations: [MockTestComponent], exports: [MockTestComponent]}
});
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.testCmpCtrl.testField).toBe('overwritten');
});
});
describe('nested module overrides using TestBed.overrideModule', () => {
// Set up an NgModule hierarchy with two modules, A and B, each with their own component.
// Module B additionally re-exports module A. Also declare two mock components which can be
// used in tests to verify that overrides within this hierarchy are working correctly.
// ModuleA content:
@Component({
selector: 'comp-a',
template: 'comp-a content',
})
class CompA {
}
@Component({
selector: 'comp-a',
template: 'comp-a mock content',
})
class MockCompA {
}
@NgModule({
declarations: [CompA],
exports: [CompA],
})
class ModuleA {
}
// ModuleB content:
@Component({
selector: 'comp-b',
template: 'comp-b content',
})
class CompB {
}
@Component({
selector: 'comp-b',
template: 'comp-b mock content',
})
class MockCompB {
}
@NgModule({
imports: [ModuleA],
declarations: [CompB],
exports: [CompB, ModuleA],
})
class ModuleB {
}
// AppModule content:
@Component({
selector: 'app',
template: `
<comp-a></comp-a>
<comp-b></comp-b>
`,
})
class App {
}
@NgModule({
imports: [ModuleB],
exports: [ModuleB],
})
class AppModule {
}
it('should detect nested module override', () => {
TestBed
.configureTestingModule({
declarations: [App],
// AppModule -> ModuleB -> ModuleA (to be overridden)
imports: [AppModule],
})
.overrideModule(ModuleA, {
remove: {declarations: [CompA], exports: [CompA]},
add: {declarations: [MockCompA], exports: [MockCompA]}
})
.compileComponents();
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
// CompA is overridden, expect mock content.
expect(fixture.nativeElement.textContent).toContain('comp-a mock content');
// CompB is not overridden, expect original content.
expect(fixture.nativeElement.textContent).toContain('comp-b content');
});
it('should detect chained modules override', () => {
TestBed
.configureTestingModule({
declarations: [App],
// AppModule -> ModuleB (to be overridden) -> ModuleA (to be overridden)
imports: [AppModule],
})
.overrideModule(ModuleA, {
remove: {declarations: [CompA], exports: [CompA]},
add: {declarations: [MockCompA], exports: [MockCompA]}
})
.overrideModule(ModuleB, {
remove: {declarations: [CompB], exports: [CompB]},
add: {declarations: [MockCompB], exports: [MockCompB]}
})
.compileComponents();
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
// Both CompA and CompB are overridden, expect mock content for both.
expect(fixture.nativeElement.textContent).toContain('comp-a mock content');
expect(fixture.nativeElement.textContent).toContain('comp-b mock content');
});
});
describe('multi providers', () => {
const multiToken = new InjectionToken<string[]>('multiToken');
const singleToken = new InjectionToken<string>('singleToken');
const multiTokenToOverrideAtModuleLevel =
new InjectionToken<string[]>('moduleLevelMultiOverride');
@NgModule({providers: [{provide: multiToken, useValue: 'valueFromModule', multi: true}]})
class MyModule {
}
@NgModule({
providers: [
{provide: singleToken, useValue: 't1'}, {
provide: multiTokenToOverrideAtModuleLevel,
useValue: 'multiTokenToOverrideAtModuleLevelOriginal',
multi: true
},
{provide: multiToken, useValue: 'valueFromModule2', multi: true},
{provide: multiToken, useValue: 'secondValueFromModule2', multi: true}
]
})
class MyModule2 {
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MyModule, {
ngModule: MyModule2,
providers:
[{provide: multiTokenToOverrideAtModuleLevel, useValue: 'override', multi: true}]
}
],
});
});
it('is preserved when other provider is overridden', () => {
TestBed.overrideProvider(singleToken, {useValue: ''});
expect(TestBed.inject(multiToken).length).toEqual(3);
expect(TestBed.inject(multiTokenToOverrideAtModuleLevel).length).toEqual(2);
expect(TestBed.inject(multiTokenToOverrideAtModuleLevel)).toEqual([
'multiTokenToOverrideAtModuleLevelOriginal', 'override'
]);
});
it('overridden with an array', () => {
const overrideValue = ['override'];
TestBed.overrideProvider(multiToken, {useValue: overrideValue, multi: true} as any);
const value = TestBed.inject(multiToken);
expect(value.length).toEqual(overrideValue.length);
expect(value).toEqual(overrideValue);
});
it('overridden with a non-array', () => {
// This is actually invalid because multi providers return arrays. We have this here so we can
// ensure Ivy behaves the same as VE does currently.
const overrideValue = 'override';
TestBed.overrideProvider(multiToken, {useValue: overrideValue, multi: true} as any);
const value = TestBed.inject(multiToken);
expect(value.length).toEqual(overrideValue.length);
expect(value).toEqual(overrideValue as {} as string[]);
});
});
describe('overrides providers in ModuleWithProviders', () => {
const TOKEN = new InjectionToken<string[]>('token');
@NgModule()
class MyMod {
static multi = false;
static forRoot() {
return {
ngModule: MyMod,
providers: [{provide: TOKEN, multi: MyMod.multi, useValue: 'forRootValue'}]
};
}
}
beforeEach(() => MyMod.multi = true);
it('when provider is a "regular" provider', () => {
MyMod.multi = false;
@NgModule({imports: [MyMod.forRoot()]})
class MyMod2 {
}
TestBed.configureTestingModule({imports: [MyMod2]});
TestBed.overrideProvider(TOKEN, {useValue: ['override']});
expect(TestBed.inject(TOKEN)).toEqual(['override']);
});
it('when provider is multi', () => {
@NgModule({imports: [MyMod.forRoot()]})
class MyMod2 {
}
TestBed.configureTestingModule({imports: [MyMod2]});
TestBed.overrideProvider(TOKEN, {useValue: ['override']});
expect(TestBed.inject(TOKEN)).toEqual(['override']);
});
it('restores the original value', () => {
@NgModule({imports: [MyMod.forRoot()]})
class MyMod2 {
}
TestBed.configureTestingModule({imports: [MyMod2]});
TestBed.overrideProvider(TOKEN, {useValue: ['override']});
expect(TestBed.inject(TOKEN)).toEqual(['override']);
TestBed.resetTestingModule();
TestBed.configureTestingModule({imports: [MyMod2]});
expect(TestBed.inject(TOKEN)).toEqual(['forRootValue']);
});
});
it('should allow overriding a provider defined via ModuleWithProviders (using TestBed.overrideProvider)',
() => {
const serviceOverride = {
get() {
return 'override';
},
};
@Injectable({providedIn: 'root'})
class MyService {
get() {
return 'original';
}
}
@NgModule({})
class MyModule {
static forRoot(): ModuleWithProviders<MyModule> {
return {
ngModule: MyModule,
providers: [MyService],
};
}
}
TestBed.overrideProvider(MyService, {useValue: serviceOverride});
TestBed.configureTestingModule({
imports: [MyModule.forRoot()],
});
const service = TestBed.inject(MyService);
expect(service.get()).toEqual('override');
});
it('should handle overrides for a provider that has `ChangeDetectorRef` as a dependency', () => {
// Note: we specifically check an @Injectable with `ChangeDetectorRef` here due to the fact that
// in Ivy there is a special instruction that injects `ChangeDetectorRef` token for Pipes
// (ɵɵinjectPipeChangeDetectorRef) and using that function for other types causes problems,
// for example when we try to override an @Injectable. The test below captures a use-case that
// triggers a problem in case incompatible function is used to inject `ChangeDetectorRef` as a
// dependency.
@Injectable({providedIn: 'root'})
class MyService {
token = 'original';
constructor(public cdr: ChangeDetectorRef) {}
}
TestBed.configureTestingModule({});
TestBed.overrideProvider(MyService, {useValue: {token: 'override'}});
const service = TestBed.inject(MyService);
expect(service.token).toBe('override');
});
it('should allow overriding a provider defined via ModuleWithProviders (using TestBed.configureTestingModule)',
() => {
const serviceOverride = {
get() {
return 'override';
},
};
@Injectable({providedIn: 'root'})
class MyService {
get() {
return 'original';
}
}
@NgModule({})
class MyModule {
static forRoot(): ModuleWithProviders<MyModule> {
return {
ngModule: MyModule,
providers: [MyService],
};
}
}
TestBed.configureTestingModule({
imports: [MyModule.forRoot()],
providers: [{provide: MyService, useValue: serviceOverride}],
});
const service = TestBed.inject(MyService);
expect(service.get()).toEqual('override');
});
it('overrides injectable that is using providedIn: AModule', () => {
@NgModule()
class ServiceModule {
}
@Injectable({providedIn: ServiceModule})
class Service {
}
const fake = 'fake';
TestBed.overrideProvider(Service, {useValue: fake});
// Create an injector whose source is the ServiceModule, not DynamicTestModule.
const ngModuleFactory = TestBed.inject(Compiler).compileModuleSync(ServiceModule);
const injector = ngModuleFactory.create(TestBed.inject(Injector)).injector;
const service = injector.get(Service);
expect(service).toBe(fake);
});
it('allow to override multi provider', () => {
const MY_TOKEN = new InjectionToken('MyProvider');
class MyProvider {}
@Component({selector: 'my-comp', template: ``})
class MyComp {
constructor(@Inject(MY_TOKEN) public myProviders: MyProvider[]) {}
}
TestBed.configureTestingModule({
declarations: [MyComp],
providers: [{provide: MY_TOKEN, useValue: {value: 'old provider'}, multi: true}]
});
const multiOverride = {useValue: [{value: 'new provider'}], multi: true};
TestBed.overrideProvider(MY_TOKEN, multiOverride as any);
const fixture = TestBed.createComponent(MyComp);
expect(fixture.componentInstance.myProviders).toEqual([{value: 'new provider'}]);
});
it('should resolve components that are extended by other components', () => {
// SimpleApp uses SimpleCmp in its template, which is extended by InheritedCmp
const simpleApp = TestBed.createComponent(SimpleApp);
simpleApp.detectChanges();
expect(simpleApp.nativeElement).toHaveText('simple - inherited');
});
it('should not trigger change detection for ComponentA while calling TestBed.createComponent for ComponentB',
() => {
const log: string[] = [];
@Component({
selector: 'comp-a',
template: '...',
})
class CompA {
@Input() inputA: string = '';
ngOnInit() {
log.push('CompA:ngOnInit', this.inputA);
}
}
@Component({
selector: 'comp-b',
template: '...',
})
class CompB {
@Input() inputB: string = '';
ngOnInit() {
log.push('CompB:ngOnInit', this.inputB);
}
}
TestBed.configureTestingModule({declarations: [CompA, CompB]});
log.length = 0;
const appA = TestBed.createComponent(CompA);
appA.componentInstance.inputA = 'a';
appA.autoDetectChanges();
expect(log).toEqual(['CompA:ngOnInit', 'a']);
log.length = 0;
const appB = TestBed.createComponent(CompB);
appB.componentInstance.inputB = 'b';
appB.autoDetectChanges();
expect(log).toEqual(['CompB:ngOnInit', 'b']);
});
it('should resolve components without async resources synchronously', (done) => {
TestBed
.configureTestingModule({
declarations: [ComponentWithInlineTemplate],
})
.compileComponents()
.then(done)
.catch(error => {
// This should not throw any errors. If an error is thrown, the test will fail.
// Specifically use `catch` here to mark the test as done and *then* throw the error
// so that the test isn't treated as a timeout.
done();
throw error;
});
// Intentionally call `createComponent` before `compileComponents` is resolved. We want this to
// work for components that don't have any async resources (templateUrl, styleUrls).
TestBed.createComponent(ComponentWithInlineTemplate);
});
it('should be able to override the ErrorHandler via an import', () => {
class CustomErrorHandler {}
@NgModule({providers: [{provide: ErrorHandler, useClass: CustomErrorHandler}]})
class ProvidesErrorHandler {
}
getTestBed().resetTestingModule();
TestBed.configureTestingModule({imports: [ProvidesErrorHandler, HelloWorldModule]});
expect(TestBed.inject(ErrorHandler)).toEqual(jasmine.any(CustomErrorHandler));
});
it('should throw errors in CD', () => {
@Component({selector: 'my-comp', template: ''})
class MyComp {
name!: {hello: string};
ngOnInit() {
// this should throw because this.name is undefined
this.name.hello = 'hello';
}
}
TestBed.configureTestingModule({declarations: [MyComp]});
expect(() => {
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
}).toThrowError();
});
// TODO(FW-1245): properly fix issue where errors in listeners aren't thrown and don't cause
// tests to fail. This is an issue in both View Engine and Ivy, and may require a breaking
// change to completely fix (since simple re-throwing breaks handlers in ngrx, etc).
xit('should throw errors in listeners', () => {
@Component({selector: 'my-comp', template: '<button (click)="onClick()">Click me</button>'})
class MyComp {
name!: {hello: string};
onClick() {
// this should throw because this.name is undefined
this.name.hello = 'hello';
}
}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
expect(() => {
const button = fixture.nativeElement.querySelector('button');
button.click();
}).toThrowError();
});
onlyInIvy('TestBed new feature to allow declaration and import of component')
.it('should allow both the declaration and import of a component into the testing module',
() => {
// This test validates that a component (Outer) which is both declared and imported
// (via its module) in the testing module behaves correctly. That is:
//
// 1) the component should be compiled in the scope of its original module.
//
// This condition is tested by having the component (Outer) use another component
// (Inner) within its template. Thus, if it's compiled in the correct scope then the
// text 'Inner' from the template of (Inner) should appear in the result.
//
// 2) the component should be available in the TestingModule scope.
//
// This condition is tested by attempting to use the component (Outer) inside a test
// fixture component (Fixture) which is declared in the testing module only.
@Component({
selector: 'inner',
template: 'Inner',
})
class Inner {
}
@Component({
selector: 'outer',
template: '<inner></inner>',
})
class Outer {
}
@NgModule({
declarations: [Inner, Outer],
})
class Module {
}
@Component({
template: '<outer></outer>',
selector: 'fixture',
})
class Fixture {
}
TestBed.configureTestingModule({
declarations: [Outer, Fixture],
imports: [Module],
});
const fixture = TestBed.createComponent(Fixture);
// The Outer component should have its template stamped out, and that template should
// include a correct instance of the Inner component with the 'Inner' text from its
// template.
expect(fixture.nativeElement.innerHTML).toEqual('<outer><inner>Inner</inner></outer>');
});
onlyInIvy('Ivy-specific errors').describe('checking types before compiling them', () => {
@Directive({
selector: 'my-dir',
})
class MyDir {
}
@NgModule()
class MyModule {
}
// [decorator, type, overrideFn]
const cases: [string, Type<any>, string][] = [
['Component', MyDir, 'overrideComponent'],
['NgModule', MyDir, 'overrideModule'],
['Pipe', MyModule, 'overridePipe'],
['Directive', MyModule, 'overrideDirective'],
];
cases.forEach(([decorator, type, overrideFn]) => {
it(`should throw an error in case invalid type is used in ${overrideFn} function`, () => {
TestBed.configureTestingModule({declarations: [MyDir]});
expect(() => {
(TestBed as any)[overrideFn](type, {});
TestBed.createComponent(type);
}).toThrowError(new RegExp(`class doesn't have @${decorator} decorator`, 'g'));
});
});
});
onlyInIvy('TestBed should handle AOT pre-compiled Components')
.describe('AOT pre-compiled components', () => {
/**
* Function returns a class that represents AOT-compiled version of the following Component:
*
* @Component({
* selector: 'comp',
* templateUrl: './template.ng.html',
* styleUrls: ['./style.css']
* })
* class ComponentClass {}
*
* This is needed to closer match the behavior of AOT pre-compiled components (compiled
* outside of TestBed) without changing TestBed state and/or Component metadata to compile
* them via TestBed with external resources.
*/
const getAOTCompiledComponent = () => {
class ComponentClass {
static ɵfac = () => new ComponentClass();
static ɵcmp = defineComponent({
type: ComponentClass,
selectors: [['comp']],
decls: 1,
vars: 0,
template:
(rf: any, ctx: any) => {
if (rf & 1) {
text(0, 'Some template');
}
},
styles: ['body { margin: 0; }']
});
}
setClassMetadata(
ComponentClass, [{
type: Component,
args: [{
selector: 'comp',
templateUrl: './template.ng.html',
styleUrls: ['./style.css'],
}]
}],
null, null);
return ComponentClass;
};
it('should have an ability to override template', () => {
const SomeComponent = getAOTCompiledComponent();
TestBed.configureTestingModule({declarations: [SomeComponent]});
TestBed.overrideTemplateUsingTestingModule(SomeComponent, 'Template override');
const fixture = TestBed.createComponent(SomeComponent);
expect(fixture.nativeElement.innerHTML).toBe('Template override');
});
it('should have an ability to override template with empty string', () => {
const SomeComponent = getAOTCompiledComponent();
TestBed.configureTestingModule({declarations: [SomeComponent]});
TestBed.overrideTemplateUsingTestingModule(SomeComponent, '');
const fixture = TestBed.createComponent(SomeComponent);
expect(fixture.nativeElement.innerHTML).toBe('');
});
it('should allow component in both in declarations and imports', () => {
const SomeComponent = getAOTCompiledComponent();
// This is an AOT compiled module which declares (but does not export) SomeComponent.
class ModuleClass {
static ɵmod = defineNgModule({
type: ModuleClass,
declarations: [SomeComponent],
});