1- import { inject , async , ComponentFixture , TestBed } from '@angular/core/testing' ;
1+ import {
2+ inject ,
3+ async ,
4+ fakeAsync ,
5+ flushMicrotasks ,
6+ ComponentFixture ,
7+ TestBed ,
8+ } from '@angular/core/testing' ;
29import { NgModule , Component , Directive , ViewChild , ViewContainerRef } from '@angular/core' ;
310import { MdDialog , MdDialogModule } from './dialog' ;
411import { OverlayContainer } from '../core' ;
@@ -100,6 +107,55 @@ describe('MdDialog', () => {
100107
101108 expect ( overlayContainerElement . querySelector ( 'md-dialog-container' ) ) . toBeFalsy ( ) ;
102109 } ) ;
110+
111+ describe ( 'focus management' , ( ) => {
112+
113+ // When testing focus, all of the elements must be in the DOM.
114+ beforeEach ( ( ) => {
115+ document . body . appendChild ( overlayContainerElement ) ;
116+ } ) ;
117+
118+ afterEach ( ( ) => {
119+ document . body . removeChild ( overlayContainerElement ) ;
120+ } ) ;
121+
122+ it ( 'should focus the first tabbable element of the dialog on open' , fakeAsync ( ( ) => {
123+ let config = new MdDialogConfig ( ) ;
124+ config . viewContainerRef = testViewContainerRef ;
125+
126+ dialog . open ( PizzaMsg , config ) ;
127+ viewContainerFixture . detectChanges ( ) ;
128+ flushMicrotasks ( ) ;
129+
130+ expect ( document . activeElement . tagName )
131+ . toBe ( 'INPUT' , 'Expected first tabbable element (input) in the dialog to be focused.' ) ;
132+ } ) ) ;
133+
134+ it ( 'should re-focus trigger element when dialog closes' , fakeAsync ( ( ) => {
135+ // Create a element that has focus before the dialog is opened.
136+ let button = document . createElement ( 'button' ) ;
137+ button . id = 'dialog-trigger' ;
138+ document . body . appendChild ( button ) ;
139+ button . focus ( ) ;
140+
141+ let config = new MdDialogConfig ( ) ;
142+ config . viewContainerRef = testViewContainerRef ;
143+
144+ let dialogRef = dialog . open ( PizzaMsg , config ) ;
145+ viewContainerFixture . detectChanges ( ) ;
146+ flushMicrotasks ( ) ;
147+
148+ expect ( document . activeElement . id )
149+ . not . toBe ( 'dialog-trigger' , 'Expected the focus to change when dialog was opened.' ) ;
150+
151+ dialogRef . close ( ) ;
152+ viewContainerFixture . detectChanges ( ) ;
153+ flushMicrotasks ( ) ;
154+
155+ expect ( document . activeElement . id )
156+ . toBe ( 'dialog-trigger' , 'Expected that the trigger was refocused after dialog close' ) ;
157+ } ) ) ;
158+ } ) ;
103159} ) ;
104160
105161
@@ -121,7 +177,7 @@ class ComponentWithChildViewContainer {
121177}
122178
123179/** Simple component for testing ComponentPortal. */
124- @Component ( { template : '<p>Pizza</p>' } )
180+ @Component ( { template : '<p>Pizza</p> <input> <button>Close</button> ' } )
125181class PizzaMsg {
126182 constructor ( public dialogRef : MdDialogRef < PizzaMsg > ) { }
127183}
0 commit comments