-
Notifications
You must be signed in to change notification settings - Fork 24.7k
/
debug_node_spec.ts
1091 lines (877 loc) Β· 35.5 KB
/
debug_node_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 Inc. 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, NgIfContext, Ι΅getDOM as getDOM} from '@angular/common';
import {Component, DebugElement, DebugNode, Directive, ElementRef, EmbeddedViewRef, EventEmitter, HostBinding, Injectable, Input, NO_ERRORS_SCHEMA, OnInit, Output, Renderer2, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core';
import {ComponentFixture, TestBed, async} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {hasClass} from '@angular/platform-browser/testing/src/browser_util';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {ivyEnabled} from '@angular/private/testing';
@Injectable()
class Logger {
logs: string[];
constructor() { this.logs = []; }
add(thing: string) { this.logs.push(thing); }
}
@Directive({selector: '[message]', inputs: ['message']})
class MessageDir {
logger: Logger;
constructor(logger: Logger) { this.logger = logger; }
set message(newMessage: string) { this.logger.add(newMessage); }
}
@Component({
selector: 'child-comp',
template: `<div class="child" message="child">
<span class="childnested" message="nestedchild">Child</span>
</div>
<span class="child" [innerHtml]="childBinding"></span>`,
})
class ChildComp {
childBinding: string;
constructor() { this.childBinding = 'Original'; }
}
@Component({
selector: 'parent-comp',
viewProviders: [Logger],
template: `<div class="parent" message="parent">
<span class="parentnested" message="nestedparent">Parent</span>
</div>
<span class="parent" [innerHtml]="parentBinding"></span>
<child-comp class="child-comp-class"></child-comp>`,
})
class ParentComp {
parentBinding: string;
constructor() { this.parentBinding = 'OriginalParent'; }
}
@Directive({selector: 'custom-emitter', outputs: ['myevent']})
class CustomEmitter {
myevent: EventEmitter<any>;
constructor() { this.myevent = new EventEmitter(); }
}
@Component({
selector: 'events-comp',
template: `<button (click)="handleClick()"></button>
<custom-emitter (myevent)="handleCustom()"></custom-emitter>`,
})
class EventsComp {
clicked: boolean;
customed: boolean;
constructor() {
this.clicked = false;
this.customed = false;
}
handleClick() { this.clicked = true; }
handleCustom() { this.customed = true; }
}
@Component({
selector: 'cond-content-comp',
viewProviders: [Logger],
template: `<div class="child" message="child" *ngIf="myBool"><ng-content></ng-content></div>`,
})
class ConditionalContentComp {
myBool: boolean = false;
}
@Component({
selector: 'conditional-parent-comp',
viewProviders: [Logger],
template: `<span class="parent" [innerHtml]="parentBinding"></span>
<cond-content-comp class="cond-content-comp-class">
<span class="from-parent"></span>
</cond-content-comp>`,
})
class ConditionalParentComp {
parentBinding: string;
constructor() { this.parentBinding = 'OriginalParent'; }
}
@Component({
selector: 'using-for',
viewProviders: [Logger],
template: `<span *ngFor="let thing of stuff" [innerHtml]="thing"></span>
<ul message="list">
<li *ngFor="let item of stuff" [innerHtml]="item"></li>
</ul>`,
})
class UsingFor {
stuff: string[];
constructor() { this.stuff = ['one', 'two', 'three']; }
}
@Directive({selector: '[mydir]', exportAs: 'mydir'})
class MyDir {
}
@Component({
selector: 'locals-comp',
template: `
<div mydir #alice="mydir"></div>
`,
})
class LocalsComp {
}
@Component({
selector: 'bank-account',
template: `
Bank Name: {{bank}}
Account Id: {{id}}
`,
host: {
'class': 'static-class',
'[class.absent-class]': 'false',
'[class.present-class]': 'true',
},
})
class BankAccount {
// TODO(issue/24571): remove '!'.
@Input() bank !: string;
// TODO(issue/24571): remove '!'.
@Input('account') id !: string;
// TODO(issue/24571): remove '!'.
normalizedBankName !: string;
}
@Component({
template: `
<div class="content" #content>Some content</div>
`
})
class SimpleContentComp {
@ViewChild('content', {static: false}) content !: ElementRef;
}
@Component({
selector: 'test-app',
template: `
<bank-account bank="RBC"
account="4747"
[style.width.px]="width"
[style.color]="color"
[class.closed]="isClosed"
[class.open]="!isClosed"></bank-account>
`,
})
class TestApp {
width = 200;
color = 'red';
isClosed = true;
}
@Component({selector: 'test-cmpt', template: ``})
class TestCmpt {
}
@Component({selector: 'host-class-binding', template: ''})
class HostClassBindingCmp {
@HostBinding('class')
hostClasses = 'class-one class-two';
}
@Component({selector: 'test-cmpt-vcref', template: `<div></div>`})
class TestCmptWithViewContainerRef {
constructor(private vcref: ViewContainerRef) {}
}
@Component({
template: `
<button
[disabled]="disabled"
[tabIndex]="tabIndex"
[title]="title">Click me</button>
`
})
class TestCmptWithPropBindings {
disabled = true;
tabIndex = 1337;
title = 'hello';
}
{
describe('debug element', () => {
let fixture: ComponentFixture<any>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ChildComp,
ConditionalContentComp,
ConditionalParentComp,
CustomEmitter,
EventsComp,
LocalsComp,
MessageDir,
MyDir,
ParentComp,
TestApp,
UsingFor,
BankAccount,
TestCmpt,
HostClassBindingCmp,
TestCmptWithViewContainerRef,
SimpleContentComp,
TestCmptWithPropBindings,
],
providers: [Logger],
schemas: [NO_ERRORS_SCHEMA],
});
}));
it('should list all child nodes', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
expect(fixture.debugElement.childNodes.length).toEqual(3);
});
it('should list all component child elements', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childEls = fixture.debugElement.children;
// The root component has 3 elements in its view.
expect(childEls.length).toEqual(3);
expect(hasClass(childEls[0].nativeElement, 'parent')).toBe(true);
expect(hasClass(childEls[1].nativeElement, 'parent')).toBe(true);
expect(hasClass(childEls[2].nativeElement, 'child-comp-class')).toBe(true);
const nested = childEls[0].children;
expect(nested.length).toEqual(1);
expect(hasClass(nested[0].nativeElement, 'parentnested')).toBe(true);
const childComponent = childEls[2];
const childCompChildren = childComponent.children;
expect(childCompChildren.length).toEqual(2);
expect(hasClass(childCompChildren[0].nativeElement, 'child')).toBe(true);
expect(hasClass(childCompChildren[1].nativeElement, 'child')).toBe(true);
const childNested = childCompChildren[0].children;
expect(childNested.length).toEqual(1);
expect(hasClass(childNested[0].nativeElement, 'childnested')).toBe(true);
});
it('should list conditional component child elements', () => {
fixture = TestBed.createComponent(ConditionalParentComp);
fixture.detectChanges();
const childEls = fixture.debugElement.children;
// The root component has 2 elements in its view.
expect(childEls.length).toEqual(2);
expect(hasClass(childEls[0].nativeElement, 'parent')).toBe(true);
expect(hasClass(childEls[1].nativeElement, 'cond-content-comp-class')).toBe(true);
const conditionalContentComp = childEls[1];
expect(conditionalContentComp.children.length).toEqual(0);
conditionalContentComp.componentInstance.myBool = true;
fixture.detectChanges();
expect(conditionalContentComp.children.length).toEqual(1);
});
it('should list child elements within viewports', () => {
fixture = TestBed.createComponent(UsingFor);
fixture.detectChanges();
const childEls = fixture.debugElement.children;
expect(childEls.length).toEqual(4);
// The 4th child is the <ul>
const list = childEls[3];
expect(list.children.length).toEqual(3);
});
it('should list element attributes', () => {
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const bankElem = fixture.debugElement.children[0];
expect(bankElem.attributes['bank']).toEqual('RBC');
expect(bankElem.attributes['account']).toEqual('4747');
});
it('should list element classes', () => {
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const bankElem = fixture.debugElement.children[0];
expect(bankElem.classes['closed']).toBe(true);
expect(bankElem.classes['open']).toBe(false);
});
it('should get element classes from host bindings', () => {
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugElement = fixture.debugElement.children[0];
expect(debugElement.classes['present-class'])
.toBe(true, 'Expected bound host CSS class "present-class" to be present');
expect(debugElement.classes['absent-class'])
.toBe(false, 'Expected bound host CSS class "absent-class" to be absent');
});
it('should list element styles', () => {
fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const bankElem = fixture.debugElement.children[0];
expect(bankElem.styles['width']).toEqual('200px');
expect(bankElem.styles['color']).toEqual('red');
});
it('should query child elements by css', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childTestEls = fixture.debugElement.queryAll(By.css('child-comp'));
expect(childTestEls.length).toBe(1);
expect(hasClass(childTestEls[0].nativeElement, 'child-comp-class')).toBe(true);
});
it('should query child elements by directive', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childTestEls = fixture.debugElement.queryAll(By.directive(MessageDir));
expect(childTestEls.length).toBe(4);
expect(hasClass(childTestEls[0].nativeElement, 'parent')).toBe(true);
expect(hasClass(childTestEls[1].nativeElement, 'parentnested')).toBe(true);
expect(hasClass(childTestEls[2].nativeElement, 'child')).toBe(true);
expect(hasClass(childTestEls[3].nativeElement, 'childnested')).toBe(true);
});
it('should query projected child elements by directive', () => {
@Directive({selector: 'example-directive-a'})
class ExampleDirectiveA {
}
@Component({
selector: 'wrapper-component',
template: `
<ng-content select="example-directive-a"></ng-content>
`
})
class WrapperComponent {
}
TestBed.configureTestingModule({
declarations: [
WrapperComponent,
ExampleDirectiveA,
]
});
TestBed.overrideTemplate(TestApp, `<wrapper-component>
<div></div>
<example-directive-a></example-directive-a>
</wrapper-component>`);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugElement = fixture.debugElement.query(By.directive(ExampleDirectiveA));
expect(debugElement).toBeTruthy();
});
it('should query re-projected child elements by directive', () => {
@Directive({selector: 'example-directive-a'})
class ExampleDirectiveA {
}
@Component({
selector: 'proxy-component',
template: `
<ng-content></ng-content>
`
})
class ProxyComponent {
}
@Component({
selector: 'wrapper-component',
template: `
<proxy-component>
<ng-content select="div"></ng-content>
<ng-content select="example-directive-a"></ng-content>
</proxy-component>
`
})
class WrapperComponent {
}
TestBed.configureTestingModule({
declarations: [
ProxyComponent,
WrapperComponent,
ExampleDirectiveA,
]
});
TestBed.overrideTemplate(TestApp, `<wrapper-component>
<div></div>
<example-directive-a></example-directive-a>
</wrapper-component>`);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugElements = fixture.debugElement.queryAll(By.directive(ExampleDirectiveA));
expect(debugElements.length).toBe(1);
});
it('should query directives on containers before directives in a view', () => {
@Directive({selector: '[text]'})
class TextDirective {
@Input() text: string|undefined;
}
TestBed.configureTestingModule({declarations: [TextDirective]});
TestBed.overrideTemplate(
TestApp,
`<ng-template text="first" [ngIf]="true"><div text="second"></div></ng-template>`);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugNodes = fixture.debugElement.queryAllNodes(By.directive(TextDirective));
expect(debugNodes.length).toBe(2);
expect(debugNodes[0].injector.get(TextDirective).text).toBe('first');
expect(debugNodes[1].injector.get(TextDirective).text).toBe('second');
});
it('should query directives on views moved in the DOM', () => {
@Directive({selector: '[text]'})
class TextDirective {
@Input() text: string|undefined;
}
@Directive({selector: '[moveView]'})
class ViewManipulatingDirective {
constructor(private _vcRef: ViewContainerRef, private _tplRef: TemplateRef<any>) {}
insert() { this._vcRef.createEmbeddedView(this._tplRef); }
removeFromTheDom() {
const viewRef = this._vcRef.get(0) as EmbeddedViewRef<any>;
viewRef.rootNodes.forEach(rootNode => { getDOM().remove(rootNode); });
}
}
TestBed.configureTestingModule({declarations: [TextDirective, ViewManipulatingDirective]});
TestBed.overrideTemplate(
TestApp, `<ng-template text="first" moveView><div text="second"></div></ng-template>`);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const viewMover =
fixture.debugElement.queryAllNodes(By.directive(ViewManipulatingDirective))[0]
.injector.get(ViewManipulatingDirective);
let debugNodes = fixture.debugElement.queryAllNodes(By.directive(TextDirective));
// we've got just one directive on <ng-template>
expect(debugNodes.length).toBe(1);
expect(debugNodes[0].injector.get(TextDirective).text).toBe('first');
// insert a view - now we expect to find 2 directive instances
viewMover.insert();
fixture.detectChanges();
debugNodes = fixture.debugElement.queryAllNodes(By.directive(TextDirective));
expect(debugNodes.length).toBe(2);
// remove a view from the DOM (equivalent to moving it around)
// the logical tree is the same but DOM has changed
viewMover.removeFromTheDom();
debugNodes = fixture.debugElement.queryAllNodes(By.directive(TextDirective));
expect(debugNodes.length).toBe(2);
expect(debugNodes[0].injector.get(TextDirective).text).toBe('first');
expect(debugNodes[1].injector.get(TextDirective).text).toBe('second');
});
it('DebugElement.query should work with dynamically created elements', () => {
@Directive({
selector: '[dir]',
})
class MyDir {
@Input('dir') dir: number|undefined;
constructor(renderer: Renderer2, element: ElementRef) {
const div = renderer.createElement('div');
div.classList.add('myclass');
renderer.appendChild(element.nativeElement, div);
}
}
@Component({
selector: 'app-test',
template: '<div dir></div>',
})
class MyComponent {
}
TestBed.configureTestingModule({declarations: [MyComponent, MyDir]});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.myclass'))).toBeTruthy();
});
it('DebugElement.query should work with dynamically created descendant elements', () => {
@Directive({
selector: '[dir]',
})
class MyDir {
@Input('dir') dir: number|undefined;
constructor(renderer: Renderer2, element: ElementRef) {
const outerDiv = renderer.createElement('div');
const innerDiv = renderer.createElement('div');
const div = renderer.createElement('div');
div.classList.add('myclass');
renderer.appendChild(innerDiv, div);
renderer.appendChild(outerDiv, innerDiv);
renderer.appendChild(element.nativeElement, outerDiv);
}
}
@Component({
selector: 'app-test',
template: '<div dir></div>',
})
class MyComponent {
}
TestBed.configureTestingModule({declarations: [MyComponent, MyDir]});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.myclass'))).toBeTruthy();
});
describe('DebugElement.query doesn\'t fail on elements outside Angular context', () => {
@Component({template: '<div></div>'})
class NativeEl {
constructor(private elementRef: ElementRef) {}
ngAfterViewInit() {
this.elementRef.nativeElement.children[0].appendChild(document.createElement('p'));
}
}
let el: DebugElement;
beforeEach(() => {
const fixture =
TestBed.configureTestingModule({declarations: [NativeEl]}).createComponent(NativeEl);
fixture.detectChanges();
el = fixture.debugElement;
});
it('when searching for elements by name',
() => { expect(() => el.query(e => e.name === 'any search text')).not.toThrow(); });
it('when searching for elements by their attributes', () => {
expect(() => el.query(e => e.attributes !['name'] === 'any attribute')).not.toThrow();
});
it('when searching for elements by their classes',
() => { expect(() => el.query(e => e.classes['any class'] === true)).not.toThrow(); });
it('when searching for elements by their styles', () => {
expect(() => el.query(e => e.styles['any style'] === 'any value')).not.toThrow();
});
it('when searching for elements by their properties', () => {
expect(() => el.query(e => e.properties['any prop'] === 'any value')).not.toThrow();
});
});
it('DebugElement.queryAll should pick up both elements inserted via the view and through Renderer2',
() => {
@Directive({
selector: '[dir]',
})
class MyDir {
@Input('dir') dir: number|undefined;
constructor(renderer: Renderer2, element: ElementRef) {
const div = renderer.createElement('div');
div.classList.add('myclass');
renderer.appendChild(element.nativeElement, div);
}
}
@Component({
selector: 'app-test',
template: '<div dir></div><span class="myclass"></span>',
})
class MyComponent {
}
TestBed.configureTestingModule({declarations: [MyComponent, MyDir]});
const fixture = TestBed.createComponent(MyComponent);
fixture.detectChanges();
const results = fixture.debugElement.queryAll(By.css('.myclass'));
expect(results.map(r => r.nativeElement.nodeName.toLowerCase())).toEqual(['div', 'span']);
});
it('should list providerTokens', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
expect(fixture.debugElement.providerTokens).toContain(Logger);
});
it('should list locals', () => {
fixture = TestBed.createComponent(LocalsComp);
fixture.detectChanges();
expect(fixture.debugElement.children[0].references !['alice']).toBeAnInstanceOf(MyDir);
});
it('should allow injecting from the element injector', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
expect((<Logger>(fixture.debugElement.children[0].injector.get(Logger))).logs).toEqual([
'parent', 'nestedparent', 'child', 'nestedchild'
]);
});
it('should list event listeners', () => {
fixture = TestBed.createComponent(EventsComp);
fixture.detectChanges();
expect(fixture.debugElement.children[0].listeners.length).toEqual(1);
expect(fixture.debugElement.children[1].listeners.length).toEqual(1);
});
it('should trigger event handlers', () => {
fixture = TestBed.createComponent(EventsComp);
fixture.detectChanges();
expect(fixture.componentInstance.clicked).toBe(false);
expect(fixture.componentInstance.customed).toBe(false);
fixture.debugElement.children[0].triggerEventHandler('click', <Event>{});
expect(fixture.componentInstance.clicked).toBe(true);
fixture.debugElement.children[1].triggerEventHandler('myevent', <Event>{});
expect(fixture.componentInstance.customed).toBe(true);
});
it('should include classes in properties.className', () => {
fixture = TestBed.createComponent(HostClassBindingCmp);
fixture.detectChanges();
const debugElement = fixture.debugElement;
expect(debugElement.properties.className).toBe('class-one class-two');
fixture.componentInstance.hostClasses = 'class-three';
fixture.detectChanges();
expect(debugElement.properties.className).toBe('class-three');
fixture.componentInstance.hostClasses = '';
fixture.detectChanges();
expect(debugElement.properties.className).toBeFalsy();
});
it('should preserve the type of the property values', () => {
const fixture = TestBed.createComponent(TestCmptWithPropBindings);
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('button'));
expect(button.properties).toEqual({disabled: true, tabIndex: 1337, title: 'hello'});
});
it('should trigger events registered via Renderer2', () => {
@Component({template: ''})
class TestComponent implements OnInit {
count = 0;
eventObj: any;
constructor(private renderer: Renderer2, private elementRef: ElementRef) {}
ngOnInit() {
this.renderer.listen(this.elementRef.nativeElement, 'click', (event: any) => {
this.count++;
this.eventObj = event;
});
}
}
TestBed.configureTestingModule({declarations: [TestComponent]});
const fixture = TestBed.createComponent(TestComponent);
// Ivy depends on `eventListeners` to pick up events that haven't been registered through
// Angular templates. At the time of writing Zone.js doesn't add `eventListeners` in Node
// environments so we have to skip the test.
if (!ivyEnabled || typeof fixture.debugElement.nativeElement.eventListeners === 'function') {
const event = {value: true};
fixture.detectChanges();
fixture.debugElement.triggerEventHandler('click', event);
expect(fixture.componentInstance.count).toBe(1);
expect(fixture.componentInstance.eventObj).toBe(event);
}
});
it('should be able to trigger an event with a null value', () => {
let value = undefined;
@Component({template: '<button (click)="handleClick($event)"></button>'})
class TestComponent {
handleClick(_event: any) {
value = _event;
// Returning `false` is what causes the renderer to call `event.preventDefault`.
return false;
}
}
TestBed.configureTestingModule({declarations: [TestComponent]});
const fixture = TestBed.createComponent(TestComponent);
const button = fixture.debugElement.query(By.css('button'));
expect(() => {
button.triggerEventHandler('click', null);
fixture.detectChanges();
}).not.toThrow();
expect(value).toBeNull();
});
describe('componentInstance on DebugNode', () => {
it('should return component associated with a node if a node is a component host', () => {
TestBed.overrideTemplate(TestCmpt, `<parent-comp></parent-comp>`);
fixture = TestBed.createComponent(TestCmpt);
const debugEl = fixture.debugElement.children[0];
expect(debugEl.componentInstance).toBeAnInstanceOf(ParentComp);
});
it('should return component associated with a node if a node is a component host (content projection)',
() => {
TestBed.overrideTemplate(
TestCmpt, `<parent-comp><child-comp></child-comp></parent-comp>`);
fixture = TestBed.createComponent(TestCmpt);
const debugEl = fixture.debugElement.query(By.directive(ChildComp));
expect(debugEl.componentInstance).toBeAnInstanceOf(ChildComp);
});
it('should return host component instance if a node has no associated component and there is no component projecting this node',
() => {
TestBed.overrideTemplate(TestCmpt, `<div></div>`);
fixture = TestBed.createComponent(TestCmpt);
const debugEl = fixture.debugElement.children[0];
expect(debugEl.componentInstance).toBeAnInstanceOf(TestCmpt);
});
it('should return host component instance if a node has no associated component and there is no component projecting this node (nested embedded views)',
() => {
TestBed.overrideTemplate(TestCmpt, `
<ng-template [ngIf]="true">
<ng-template [ngIf]="true">
<div mydir></div>
</ng-template>
</ng-template>`);
fixture = TestBed.createComponent(TestCmpt);
fixture.detectChanges();
const debugEl = fixture.debugElement.query(By.directive(MyDir));
expect(debugEl.componentInstance).toBeAnInstanceOf(TestCmpt);
});
it('should return component instance that projects a given node if a node has no associated component',
() => {
TestBed.overrideTemplate(
TestCmpt, `<parent-comp><span><div></div></span></parent-comp>`);
fixture = TestBed.createComponent(TestCmpt);
const debugEl = fixture.debugElement.children[0].children[0].children[0]; // <div>
expect(debugEl.componentInstance).toBeAnInstanceOf(ParentComp);
});
});
describe('context on DebugNode', () => {
it('should return component associated with the node if both a structural directive and a component match the node',
() => {
@Component({selector: 'example-component', template: ''})
class ExampleComponent {
}
TestBed.configureTestingModule(
{imports: [CommonModule], declarations: [ExampleComponent]});
TestBed.overrideTemplate(
TestApp, '<example-component *ngIf="true"></example-component>');
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugNode = fixture.debugElement.query(By.directive(ExampleComponent));
expect(debugNode.context instanceof ExampleComponent).toBe(true);
});
it('should return structural directive context if there is a structural directive on the node',
() => {
TestBed.configureTestingModule({imports: [CommonModule]});
TestBed.overrideTemplate(TestApp, '<span *ngIf="true"></span>');
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugNode = fixture.debugElement.query(By.css('span'));
expect(debugNode.context instanceof NgIfContext).toBe(true);
});
it('should return the containing component if there is no structural directive or component on the node',
() => {
TestBed.configureTestingModule({declarations: [MyDir]});
TestBed.overrideTemplate(TestApp, '<span mydir></span>');
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const debugNode = fixture.debugElement.query(By.directive(MyDir));
expect(debugNode.context instanceof TestApp).toBe(true);
});
});
it('should be able to query for elements that are not in the same DOM tree anymore', () => {
fixture = TestBed.createComponent(SimpleContentComp);
fixture.detectChanges();
const parent = getDOM().parentElement(fixture.nativeElement) !;
const content = fixture.componentInstance.content.nativeElement;
// Move the content element outside the component
// so that it can't be reached via querySelector.
getDOM().appendChild(parent, content);
expect(fixture.debugElement.query(By.css('.content'))).toBeTruthy();
getDOM().remove(content);
});
it('should support components with ViewContainerRef', () => {
fixture = TestBed.createComponent(TestCmptWithViewContainerRef);
const divEl = fixture.debugElement.query(By.css('div'));
expect(divEl).not.toBeNull();
});
it('should support querying on any debug element', () => {
TestBed.overrideTemplate(TestCmpt, `<span><div id="a"><div id="b"></div></div></span>`);
fixture = TestBed.createComponent(TestCmpt);
const divA = fixture.debugElement.query(By.css('div'));
expect(divA.nativeElement.getAttribute('id')).toBe('a');
const divB = divA.query(By.css('div'));
expect(divB.nativeElement.getAttribute('id')).toBe('b');
});
it('should be an instance of DebugNode', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
expect(fixture.debugElement).toBeAnInstanceOf(DebugNode);
});
it('should return the same element when queried twice', () => {
fixture = TestBed.createComponent(ParentComp);
fixture.detectChanges();
const childTestElsFirst = fixture.debugElement.queryAll(By.css('child-comp'));
const childTestElsSecond = fixture.debugElement.queryAll(By.css('child-comp'));
expect(childTestElsFirst.length).toBe(1);
expect(childTestElsSecond[0]).toBe(childTestElsFirst[0]);
});
it('should not query the descendants of a sibling node', () => {
@Component({
selector: 'my-comp',
template: `
<div class="div.1">
<p class="p.1">
<span class="span.1">span.1</span>
<span class="span.2">span.2</span>
</p>
<p class="p.2">
<span class="span.3">span.3</span>
<span class="span.4">span.4</span>
</p>
</div>
<div class="div.2">
<p class="p.3">
<span class="span.5">span.5</span>
<span class="span.6">span.6</span>
</p>
<p class="p.4">
<span class="span.7">span.7</span>
<span class="span.8">span.8</span>
</p>
</div>
`
})
class MyComp {
}
TestBed.configureTestingModule({declarations: [MyComp]});
const fixture = TestBed.createComponent(MyComp);
fixture.detectChanges();
const firstDiv = fixture.debugElement.query(By.css('div'));
const firstDivChildren = firstDiv.queryAll(By.css('span'));
expect(firstDivChildren.map(child => child.nativeNode.textContent.trim())).toEqual([
'span.1', 'span.2', 'span.3', 'span.4'
]);
});
it('should preserve the attribute case in DebugNode.attributes', () => {
@Component({selector: 'my-icon', template: ''})
class Icon {
@Input() svgIcon: any = '';
}
@Component({template: `<my-icon svgIcon="test"></my-icon>`})
class App {
}
TestBed.configureTestingModule({declarations: [App, Icon]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
const element = fixture.debugElement.children[0];
// Assert that the camel-case attribute is correct.
expect(element.attributes.svgIcon).toBe('test');
// Make sure that we somehow didn't preserve the native lower-cased value.
expect(element.attributes.svgicon).toBeFalsy();
});
it('should include namespaced attributes in DebugNode.attributes', () => {
@Component({
template: `<div xlink:href="foo"></div>`,
})
class Comp {
}
TestBed.configureTestingModule({declarations: [Comp]});
const fixture = TestBed.createComponent(Comp);
fixture.detectChanges();