Testing an event is one of the fascinating parts of unit testing. You are creating an event without even going to the screen.
In the series of Event Testing, I am going to tell you about testing a keyDown event on window.
I am not going into a detailed description of creating a component or writing a test file. Just explaining the methods:
In Test-component.ts
// Listen keyboard shortcuts@HostListener('window:keydown', ['$event']) onKeyDown( event ) { // Esc button click if (event.keyCode === 27 && event.code === 'Escape') { this.eventFired = true; } }
In Test-component.spec.ts
it('should fire window keydown event', () => { const event: Event = new KeyboardEvent('keydown', { 'code': 'Escape' //Code for the key }); window.dispatchEvent(event); fixture.detectChanges(); expect(component.eventFired).toBeTruthy(); });
If you want any detailed description, please tell me in the comments below.