import { ComponentFixture } from '@angular/core/testing' ; export function dispatchFixtureKeyEvent ( fixture , predicate , key , indexOf = - 1 ) { const { debugElement } = fixture ; const _debugElement = indexOf > - 1 ? debugElement . queryAll ( predicate ) [ indexOf ] : debugElement . query ( predicate ) ; const event = document . createEvent ( 'KeyboardEvent' ) ; event . initEvent ( '' , true , true ) ; _debugElement . triggerEventHandler ( key , event ) ; } /** Utility to dispatch any event on a Node. */ export function dispatchEvent ( node , event ) { if ( typeof event === 'string' ) { event = createHTMLEvent ( event ) ; } node . dispatchEvent ( event ) ; return event ; } /** Shorthand to dispatch a keyboard event with a specified key code. */ export function dispatchKeyboardEvent ( node , type , keyCode , target ? ) { return dispatchEvent ( node , createKeyboardEvent ( type , keyCode , target ) ) as KeyboardEvent ; } function createHTMLEvent ( type ) { const evt = document . createEvent ( 'HTMLEvents' ) ; evt . initEvent ( type , true , true ) ; return evt ; } /** Dispatches a keydown event from an element. */ function createKeyboardEvent ( type , keyCode , target ? , key ? ) { const event = document . createEvent ( 'KeyboardEvent' ) as any ; const originalPreventDefault = event . preventDefault ; if ( event . initKeyEvent ) { event . initKeyEvent ( type , true , true , window , 0 , 0 , 0 , 0 , 0 , keyCode ) ; } else { event . initKeyboardEvent ( type , true , true , window , 0 , key , 0 , '' , false ) ; } Object . defineProperties ( event , { keyCode : { get : ( ) => keyCode } , key : { get : ( ) => key } , target : { get : ( ) => target } } ) ; event . preventDefault = function ( ) { Object . defineProperty ( event , 'defaultPrevented' , { get : ( ) => true } ) ; return originalPreventDefault . apply ( this , arguments ) ; } ; return event ; }