-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
menu.spec.ts
1684 lines (1320 loc) · 59.7 KB
/
menu.spec.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {ComponentFixture, fakeAsync, inject, TestBed, tick} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {
Component,
ElementRef,
EventEmitter,
Input,
Output,
NgZone,
TemplateRef,
ViewChild,
ViewChildren,
QueryList,
Type,
Provider,
} from '@angular/core';
import {Direction, Directionality} from '@angular/cdk/bidi';
import {OverlayContainer, Overlay} from '@angular/cdk/overlay';
import {ESCAPE, LEFT_ARROW, RIGHT_ARROW, TAB} from '@angular/cdk/keycodes';
import {
MAT_MENU_DEFAULT_OPTIONS,
MatMenu,
MatMenuModule,
MatMenuPanel,
MatMenuTrigger,
MenuPositionX,
MenuPositionY,
MatMenuItem,
} from './index';
import {MENU_PANEL_TOP_PADDING, MAT_MENU_SCROLL_STRATEGY} from './menu-trigger';
import {MatRipple} from '@angular/material/core';
import {
dispatchKeyboardEvent,
dispatchMouseEvent,
dispatchEvent,
createKeyboardEvent,
createMouseEvent,
dispatchFakeEvent,
patchElementFocus,
MockNgZone,
} from '@angular/cdk/testing';
import {Subject} from 'rxjs';
import {ScrollDispatcher} from '@angular/cdk/scrolling';
import {FocusMonitor} from '@angular/cdk/a11y';
describe('MatMenu', () => {
let overlayContainer: OverlayContainer;
let overlayContainerElement: HTMLElement;
let focusMonitor: FocusMonitor;
function createComponent<T>(component: Type<T>, providers: Provider[] = [],
declarations: any[] = []): ComponentFixture<T> {
TestBed.configureTestingModule({
imports: [MatMenuModule, NoopAnimationsModule],
declarations: [component, ...declarations],
providers
}).compileComponents();
inject([OverlayContainer, FocusMonitor], (oc: OverlayContainer, fm: FocusMonitor) => {
overlayContainer = oc;
overlayContainerElement = oc.getContainerElement();
focusMonitor = fm;
})();
return TestBed.createComponent<T>(component);
}
afterEach(inject([OverlayContainer], (currentOverlayContainer: OverlayContainer) => {
// Since we're resetting the testing module in some of the tests,
// we can potentially have multiple overlay containers.
currentOverlayContainer.ngOnDestroy();
overlayContainer.ngOnDestroy();
}));
it('should open the menu as an idempotent operation', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toBe('');
expect(() => {
fixture.componentInstance.trigger.openMenu();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('Item');
expect(overlayContainerElement.textContent).toContain('Disabled');
}).not.toThrowError();
});
it('should close the menu when a click occurs outside the menu', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
const backdrop = <HTMLElement>overlayContainerElement.querySelector('.cdk-overlay-backdrop');
backdrop.click();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toBe('');
}));
it('should be able to remove the backdrop', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.menu.hasBackdrop = false;
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeFalsy();
}));
it('should restore focus to the trigger when the menu was opened by keyboard', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
// A click without a mousedown before it is considered a keyboard open.
triggerEl.click();
fixture.detectChanges();
expect(overlayContainerElement.querySelector('.mat-menu-panel')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(triggerEl);
}));
it('should be able to set a custom class on the backdrop', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.componentInstance.backdropClass = 'custom-backdrop';
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
const backdrop = <HTMLElement>overlayContainerElement.querySelector('.cdk-overlay-backdrop');
expect(backdrop.classList).toContain('custom-backdrop');
}));
it('should restore focus to the root trigger when the menu was opened by mouse', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
expect(overlayContainerElement.querySelector('.mat-menu-panel')).toBeTruthy();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(triggerEl);
}));
it('should set the proper focus origin when restoring focus after opening by keyboard',
fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
triggerEl.click(); // A click without a mousedown before it is considered a keyboard open.
fixture.detectChanges();
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(triggerEl.classList).toContain('cdk-program-focused');
focusMonitor.stopMonitoring(triggerEl);
}));
it('should set the proper focus origin when restoring focus after opening by mouse',
fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
patchElementFocus(triggerEl);
focusMonitor.monitor(triggerEl, false);
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(triggerEl.classList).toContain('cdk-mouse-focused');
focusMonitor.stopMonitoring(triggerEl);
}));
it('should close the menu when pressing ESCAPE', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
const panel = overlayContainerElement.querySelector('.mat-menu-panel')!;
const event = createKeyboardEvent('keydown', ESCAPE);
const stopPropagationSpy = spyOn(event, 'stopPropagation').and.callThrough();
dispatchEvent(panel, event);
fixture.detectChanges();
tick(500);
expect(overlayContainerElement.textContent).toBe('');
expect(stopPropagationSpy).toHaveBeenCalled();
}));
it('should open a custom menu', () => {
const fixture = createComponent(CustomMenu, [], [CustomMenuPanel]);
fixture.detectChanges();
expect(overlayContainerElement.textContent).toBe('');
expect(() => {
fixture.componentInstance.trigger.openMenu();
fixture.componentInstance.trigger.openMenu();
expect(overlayContainerElement.textContent).toContain('Custom Menu header');
expect(overlayContainerElement.textContent).toContain('Custom Content');
}).not.toThrowError();
});
it('should set the panel direction based on the trigger direction', () => {
const fixture = createComponent(SimpleMenu, [{
provide: Directionality, useFactory: () => ({value: 'rtl'})}
], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane')!;
expect(overlayPane.getAttribute('dir')).toEqual('rtl');
});
it('should transfer any custom classes from the host to the overlay', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const menuEl = fixture.debugElement.query(By.css('mat-menu')).nativeElement;
const panel = overlayContainerElement.querySelector('.mat-menu-panel')!;
expect(menuEl.classList).not.toContain('custom-one');
expect(menuEl.classList).not.toContain('custom-two');
expect(panel.classList).toContain('custom-one');
expect(panel.classList).toContain('custom-two');
});
it('should set the "menu" role on the overlay panel', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const menuPanel = overlayContainerElement.querySelector('.mat-menu-panel');
expect(menuPanel).toBeTruthy('Expected to find a menu panel.');
const role = menuPanel ? menuPanel.getAttribute('role') : '';
expect(role).toBe('menu', 'Expected panel to have the "menu" role.');
});
it('should not throw an error on destroy', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
expect(fixture.destroy.bind(fixture)).not.toThrow();
});
it('should be able to extract the menu item text', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
expect(fixture.componentInstance.items.first.getLabel()).toBe('Item');
});
it('should filter out non-text nodes when figuring out the label', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
expect(fixture.componentInstance.items.last.getLabel()).toBe('Item with an icon');
});
it('should set the proper focus origin when opening by mouse', fakeAsync(() => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
spyOn(fixture.componentInstance.items.first, 'focus').and.callThrough();
const triggerEl = fixture.componentInstance.triggerEl.nativeElement;
dispatchFakeEvent(triggerEl, 'mousedown');
triggerEl.click();
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.items.first.focus).toHaveBeenCalledWith('mouse');
}));
it('should close the menu when using the CloseScrollStrategy', fakeAsync(() => {
const scrolledSubject = new Subject();
const fixture = createComponent(SimpleMenu, [
{provide: ScrollDispatcher, useFactory: () => ({scrolled: () => scrolledSubject})},
{
provide: MAT_MENU_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: (overlay: Overlay) => () => overlay.scrollStrategies.close()
}
], [FakeIcon]);
const trigger = fixture.componentInstance.trigger;
fixture.detectChanges();
trigger.openMenu();
fixture.detectChanges();
expect(trigger.menuOpen).toBe(true);
scrolledSubject.next();
tick(500);
expect(trigger.menuOpen).toBe(false);
}));
describe('lazy rendering', () => {
it('should be able to render the menu content lazily', fakeAsync(() => {
const fixture = createComponent(SimpleLazyMenu);
fixture.detectChanges();
fixture.componentInstance.triggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
const panel = overlayContainerElement.querySelector('.mat-menu-panel')!;
expect(panel).toBeTruthy('Expected panel to be defined');
expect(panel.textContent).toContain('Another item', 'Expected panel to have correct content');
expect(fixture.componentInstance.trigger.menuOpen).toBe(true, 'Expected menu to be open');
}));
it('should detach the lazy content when the menu is closed', fakeAsync(() => {
const fixture = createComponent(SimpleLazyMenu);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
tick(500);
expect(fixture.componentInstance.items.length).toBeGreaterThan(0);
fixture.componentInstance.trigger.closeMenu();
fixture.detectChanges();
tick(500);
fixture.detectChanges();
expect(fixture.componentInstance.items.length).toBe(0);
}));
it('should focus the first menu item when opening a lazy menu via keyboard', fakeAsync(() => {
let zone: MockNgZone;
let fixture = createComponent(SimpleLazyMenu, [{
provide: NgZone, useFactory: () => zone = new MockNgZone()
}]);
fixture.detectChanges();
// A click without a mousedown before it is considered a keyboard open.
fixture.componentInstance.triggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
zone!.simulateZoneExit();
tick();
const item = document.querySelector('.mat-menu-panel [mat-menu-item]')!;
expect(document.activeElement).toBe(item, 'Expected first item to be focused');
}));
it('should be able to open the same menu with a different context', fakeAsync(() => {
const fixture = createComponent(LazyMenuWithContext);
fixture.detectChanges();
fixture.componentInstance.triggerOne.openMenu();
fixture.detectChanges();
tick(500);
let item = overlayContainerElement.querySelector('.mat-menu-panel [mat-menu-item]')!;
expect(item.textContent!.trim()).toBe('one');
fixture.componentInstance.triggerOne.closeMenu();
fixture.detectChanges();
tick(500);
fixture.componentInstance.triggerTwo.openMenu();
fixture.detectChanges();
tick(500);
item = overlayContainerElement.querySelector('.mat-menu-panel [mat-menu-item]')!;
expect(item.textContent!.trim()).toBe('two');
}));
});
describe('positions', () => {
let fixture: ComponentFixture<PositionedMenu>;
let panel: HTMLElement;
beforeEach(() => {
fixture = createComponent(PositionedMenu);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
// Push trigger to the bottom edge of viewport,so it has space to open "above"
trigger.style.position = 'fixed';
trigger.style.top = '600px';
// Push trigger to the right, so it has space to open "before"
trigger.style.left = '100px';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
panel = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement;
});
it('should append mat-menu-before if the x position is changed', () => {
expect(panel.classList).toContain('mat-menu-before');
expect(panel.classList).not.toContain('mat-menu-after');
fixture.componentInstance.xPosition = 'after';
fixture.detectChanges();
expect(panel.classList).toContain('mat-menu-after');
expect(panel.classList).not.toContain('mat-menu-before');
});
it('should append mat-menu-above if the y position is changed', () => {
expect(panel.classList).toContain('mat-menu-above');
expect(panel.classList).not.toContain('mat-menu-below');
fixture.componentInstance.yPosition = 'below';
fixture.detectChanges();
expect(panel.classList).toContain('mat-menu-below');
expect(panel.classList).not.toContain('mat-menu-above');
});
it('should default to the "below" and "after" positions', () => {
fixture.destroy();
TestBed.resetTestingModule();
let newFixture = createComponent(SimpleMenu, [], [FakeIcon]);
newFixture.detectChanges();
newFixture.componentInstance.trigger.openMenu();
newFixture.detectChanges();
panel = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement;
expect(panel.classList).toContain('mat-menu-below');
expect(panel.classList).toContain('mat-menu-after');
});
});
describe('fallback positions', () => {
it('should fall back to "before" mode if "after" mode would not fit on screen', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
// Push trigger to the right side of viewport, so it doesn't have space to open
// in its default "after" position on the right side.
trigger.style.position = 'fixed';
trigger.style.right = '0';
trigger.style.top = '200px';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const overlayPane = getOverlayPane();
const triggerRect = trigger.getBoundingClientRect();
const overlayRect = overlayPane.getBoundingClientRect();
// In "before" position, the right sides of the overlay and the origin are aligned.
// To find the overlay left, subtract the menu width from the origin's right side.
const expectedLeft = triggerRect.right - overlayRect.width;
expect(Math.floor(overlayRect.left))
.toBe(Math.floor(expectedLeft),
`Expected menu to open in "before" position if "after" position wouldn't fit.`);
// The y-position of the overlay should be unaffected, as it can already fit vertically
expect(Math.floor(overlayRect.top))
.toBe(Math.floor(triggerRect.top),
`Expected menu top position to be unchanged if it can fit in the viewport.`);
});
it('should fall back to "above" mode if "below" mode would not fit on screen', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
// Push trigger to the bottom part of viewport, so it doesn't have space to open
// in its default "below" position below the trigger.
trigger.style.position = 'fixed';
trigger.style.bottom = '65px';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const overlayPane = getOverlayPane();
const triggerRect = trigger.getBoundingClientRect();
const overlayRect = overlayPane.getBoundingClientRect();
// In "above" position, the bottom edges of the overlay and the origin are aligned.
// To find the overlay top, subtract the menu height from the origin's bottom edge.
const expectedTop = triggerRect.bottom - overlayRect.height;
expect(Math.floor(overlayRect.top))
.toBe(Math.floor(expectedTop),
`Expected menu to open in "above" position if "below" position wouldn't fit.`);
// The x-position of the overlay should be unaffected, as it can already fit horizontally
expect(Math.floor(overlayRect.left))
.toBe(Math.floor(triggerRect.left),
`Expected menu x position to be unchanged if it can fit in the viewport.`);
});
it('should re-position menu on both axes if both defaults would not fit', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
// push trigger to the bottom, right part of viewport, so it doesn't have space to open
// in its default "after below" position.
trigger.style.position = 'fixed';
trigger.style.right = '0';
trigger.style.bottom = '0';
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const overlayPane = getOverlayPane();
const triggerRect = trigger.getBoundingClientRect();
const overlayRect = overlayPane.getBoundingClientRect();
const expectedLeft = triggerRect.right - overlayRect.width;
const expectedTop = triggerRect.bottom - overlayRect.height;
expect(Math.floor(overlayRect.left))
.toBe(Math.floor(expectedLeft),
`Expected menu to open in "before" position if "after" position wouldn't fit.`);
expect(Math.floor(overlayRect.top))
.toBe(Math.floor(expectedTop),
`Expected menu to open in "above" position if "below" position wouldn't fit.`);
});
it('should re-position a menu with custom position set', () => {
const fixture = createComponent(PositionedMenu);
fixture.detectChanges();
const trigger = fixture.componentInstance.triggerEl.nativeElement;
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const overlayPane = getOverlayPane();
const triggerRect = trigger.getBoundingClientRect();
const overlayRect = overlayPane.getBoundingClientRect();
// As designated "before" position won't fit on screen, the menu should fall back
// to "after" mode, where the left sides of the overlay and trigger are aligned.
expect(Math.floor(overlayRect.left))
.toBe(Math.floor(triggerRect.left),
`Expected menu to open in "after" position if "before" position wouldn't fit.`);
// As designated "above" position won't fit on screen, the menu should fall back
// to "below" mode, where the top edges of the overlay and trigger are aligned.
expect(Math.floor(overlayRect.top))
.toBe(Math.floor(triggerRect.top),
`Expected menu to open in "below" position if "above" position wouldn't fit.`);
});
function getOverlayPane(): HTMLElement {
return overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
}
});
describe('overlapping trigger', () => {
/**
* This test class is used to create components containing a menu.
* It provides helpers to reposition the trigger, open the menu,
* and access the trigger and overlay positions.
* Additionally it can take any inputs for the menu wrapper component.
*
* Basic usage:
* const subject = new OverlapSubject(MyComponent);
* subject.openMenu();
*/
class OverlapSubject<T extends TestableMenu> {
readonly fixture: ComponentFixture<T>;
readonly trigger: HTMLElement;
constructor(ctor: {new(): T; }, inputs: {[key: string]: any} = {}) {
this.fixture = createComponent(ctor);
Object.keys(inputs).forEach(key => this.fixture.componentInstance[key] = inputs[key]);
this.fixture.detectChanges();
this.trigger = this.fixture.componentInstance.triggerEl.nativeElement;
}
openMenu() {
this.fixture.componentInstance.trigger.openMenu();
this.fixture.detectChanges();
}
get overlayRect() {
return this.overlayPane.getBoundingClientRect();
}
get triggerRect() {
return this.trigger.getBoundingClientRect();
}
get menuPanel() {
return overlayContainerElement.querySelector('.mat-menu-panel');
}
private get overlayPane() {
return overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
}
}
let subject: OverlapSubject<OverlapMenu>;
describe('explicitly overlapping', () => {
beforeEach(() => {
subject = new OverlapSubject(OverlapMenu, {overlapTrigger: true});
});
it('positions the overlay below the trigger', () => {
subject.openMenu();
// Since the menu is overlaying the trigger, the overlay top should be the trigger top.
expect(Math.floor(subject.overlayRect.top))
.toBe(Math.floor(subject.triggerRect.top),
`Expected menu to open in default "below" position.`);
});
});
describe('not overlapping', () => {
beforeEach(() => {
subject = new OverlapSubject(OverlapMenu, {overlapTrigger: false});
});
it('positions the overlay below the trigger', () => {
subject.openMenu();
// Since the menu is below the trigger, the overlay top should be the trigger bottom.
expect(Math.floor(subject.overlayRect.top))
.toBe(Math.floor(subject.triggerRect.bottom),
`Expected menu to open directly below the trigger.`);
});
it('supports above position fall back', () => {
// Push trigger to the bottom part of viewport, so it doesn't have space to open
// in its default "below" position below the trigger.
subject.trigger.style.position = 'fixed';
subject.trigger.style.bottom = '0';
subject.openMenu();
// Since the menu is above the trigger, the overlay bottom should be the trigger top.
expect(Math.floor(subject.overlayRect.bottom))
.toBe(Math.floor(subject.triggerRect.top),
`Expected menu to open in "above" position if "below" position wouldn't fit.`);
});
it('repositions the origin to be below, so the menu opens from the trigger', () => {
subject.openMenu();
subject.fixture.detectChanges();
expect(subject.menuPanel!.classList).toContain('mat-menu-below');
expect(subject.menuPanel!.classList).not.toContain('mat-menu-above');
});
});
});
describe('animations', () => {
it('should enable ripples on items by default', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const item = fixture.debugElement.query(By.css('.mat-menu-item'));
const ripple = item.query(By.css('.mat-ripple')).injector.get<MatRipple>(MatRipple);
expect(ripple.disabled).toBe(false);
});
it('should disable ripples on disabled items', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
const items = fixture.debugElement.queryAll(By.css('.mat-menu-item'));
const ripple = items[1].query(By.css('.mat-ripple')).injector.get<MatRipple>(MatRipple);
expect(ripple.disabled).toBe(true);
});
it('should disable ripples if disableRipple is set', () => {
const fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
// The third menu item in the `SimpleMenu` component has ripples disabled.
const items = fixture.debugElement.queryAll(By.css('.mat-menu-item'));
const ripple = items[2].query(By.css('.mat-ripple')).injector.get<MatRipple>(MatRipple);
expect(ripple.disabled).toBe(true);
});
});
describe('close event', () => {
let fixture: ComponentFixture<SimpleMenu>;
beforeEach(() => {
fixture = createComponent(SimpleMenu, [], [FakeIcon]);
fixture.detectChanges();
fixture.componentInstance.trigger.openMenu();
fixture.detectChanges();
});
it('should emit an event when a menu item is clicked', () => {
const menuItem = overlayContainerElement.querySelector('[mat-menu-item]') as HTMLElement;
menuItem.click();
fixture.detectChanges();
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith('click');
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
});
it('should emit a close event when the backdrop is clicked', () => {
const backdrop = overlayContainerElement
.querySelector('.cdk-overlay-backdrop') as HTMLElement;
backdrop.click();
fixture.detectChanges();
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith(undefined);
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
});
it('should emit an event when pressing ESCAPE', () => {
const menu = overlayContainerElement.querySelector('.mat-menu-panel') as HTMLElement;
dispatchKeyboardEvent(menu, 'keydown', ESCAPE);
fixture.detectChanges();
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledWith('keydown');
expect(fixture.componentInstance.closeCallback).toHaveBeenCalledTimes(1);
});
it('should complete the callback when the menu is destroyed', () => {
const emitCallback = jasmine.createSpy('emit callback');
const completeCallback = jasmine.createSpy('complete callback');
fixture.componentInstance.menu.closed.subscribe(emitCallback, null, completeCallback);
fixture.destroy();
expect(emitCallback).toHaveBeenCalledWith(undefined);
expect(emitCallback).toHaveBeenCalledTimes(1);
expect(completeCallback).toHaveBeenCalled();
});
});
describe('nested menu', () => {
let fixture: ComponentFixture<NestedMenu>;
let instance: NestedMenu;
let overlay: HTMLElement;
let compileTestComponent = (direction: Direction = 'ltr') => {
fixture = createComponent(NestedMenu, [{
provide: Directionality, useFactory: () => ({value: direction})
}]);
fixture.detectChanges();
instance = fixture.componentInstance;
overlay = overlayContainerElement;
};
it('should set the `triggersSubmenu` flags on the triggers', () => {
compileTestComponent();
expect(instance.rootTrigger.triggersSubmenu()).toBe(false);
expect(instance.levelOneTrigger.triggersSubmenu()).toBe(true);
expect(instance.levelTwoTrigger.triggersSubmenu()).toBe(true);
});
it('should set the `parentMenu` on the sub-menu instances', () => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
expect(instance.rootMenu.parentMenu).toBeFalsy();
expect(instance.levelOneMenu.parentMenu).toBe(instance.rootMenu);
expect(instance.levelTwoMenu.parentMenu).toBe(instance.levelOneMenu);
});
it('should pass the layout direction the nested menus', () => {
compileTestComponent('rtl');
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
instance.levelOneTrigger.openMenu();
fixture.detectChanges();
instance.levelTwoTrigger.openMenu();
fixture.detectChanges();
expect(instance.rootMenu.direction).toBe('rtl');
expect(instance.levelOneMenu.direction).toBe('rtl');
expect(instance.levelTwoMenu.direction).toBe('rtl');
});
it('should emit an event when the hover state of the menu items changes', () => {
compileTestComponent();
instance.rootTrigger.openMenu();
fixture.detectChanges();
const spy = jasmine.createSpy('hover spy');
const subscription = instance.rootMenu._hovered().subscribe(spy);
const menuItems = overlay.querySelectorAll('[mat-menu-item]');
dispatchMouseEvent(menuItems[0], 'mouseenter');
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
dispatchMouseEvent(menuItems[1], 'mouseenter');
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(2);
subscription.unsubscribe();
});
it('should toggle a nested menu when its trigger is hovered', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu');
const items = Array.from(overlay.querySelectorAll('.mat-menu-panel [mat-menu-item]'));
const levelOneTrigger = overlay.querySelector('#level-one-trigger')!;
dispatchMouseEvent(levelOneTrigger, 'mouseenter');
fixture.detectChanges();
expect(levelOneTrigger.classList)
.toContain('mat-menu-item-highlighted', 'Expected the trigger to be highlighted');
expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus');
dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu');
expect(levelOneTrigger.classList)
.not.toContain('mat-menu-item-highlighted', 'Expected the trigger to not be highlighted');
}));
it('should close all the open sub-menus when the hover state is changed at the root',
fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
const items = Array.from(overlay.querySelectorAll('.mat-menu-panel [mat-menu-item]'));
const levelOneTrigger = overlay.querySelector('#level-one-trigger')!;
dispatchMouseEvent(levelOneTrigger, 'mouseenter');
fixture.detectChanges();
const levelTwoTrigger = overlay.querySelector('#level-two-trigger')! as HTMLElement;
dispatchMouseEvent(levelTwoTrigger, 'mouseenter');
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-menu-panel').length)
.toBe(3, 'Expected three open menus');
dispatchMouseEvent(items[items.indexOf(levelOneTrigger) + 1], 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-menu-panel').length)
.toBe(1, 'Expected one open menu');
}));
it('should close submenu when hovering over disabled sibling item', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
const items = fixture.debugElement.queryAll(By.directive(MatMenuItem));
dispatchFakeEvent(items[0].nativeElement, 'mouseenter');
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-menu-panel').length)
.toBe(2, 'Expected two open menus');
items[1].componentInstance.disabled = true;
fixture.detectChanges();
// Invoke the handler directly since the fake events are flaky on disabled elements.
items[1].componentInstance._handleMouseEnter();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-menu-panel').length)
.toBe(1, 'Expected one open menu');
}));
it('should not open submenu when hovering over disabled trigger', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-menu-panel').length)
.toBe(1, 'Expected one open menu');
const item = fixture.debugElement.query(By.directive(MatMenuItem));
item.componentInstance.disabled = true;
fixture.detectChanges();
// Invoke the handler directly since the fake events are flaky on disabled elements.
item.componentInstance._handleMouseEnter();
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-menu-panel').length)
.toBe(1, 'Expected to remain at one open menu');
}));
it('should open a nested menu when its trigger is clicked', () => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu');
const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement;
levelOneTrigger.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(2, 'Expected two open menus');
levelOneTrigger.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-menu-panel').length)
.toBe(2, 'Expected repeat clicks not to close the menu.');
});
it('should open and close a nested menu with arrow keys in ltr', fakeAsync(() => {
compileTestComponent();
instance.rootTriggerEl.nativeElement.click();
fixture.detectChanges();
expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1, 'Expected one open menu');
const levelOneTrigger = overlay.querySelector('#level-one-trigger')! as HTMLElement;
dispatchKeyboardEvent(levelOneTrigger, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
const panels = overlay.querySelectorAll('.mat-menu-panel');
expect(panels.length).toBe(2, 'Expected two open menus');
dispatchKeyboardEvent(panels[1], 'keydown', LEFT_ARROW);
fixture.detectChanges();
tick(500);
expect(overlay.querySelectorAll('.mat-menu-panel').length).toBe(1);