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.
Hi.. I tried it but it didnt work.. However I tried it on a HTMLInputElement...
ReplyDeleteit('should trigger "createChip()" when Enter is pressed', () => {
keyPress(page.matInput, 'Enter');
page.detectChanges();
expect(page.spies.createChip).toHaveBeenCalled();
});
keyPress(el: HTMLInputElement | HTMLTextAreaElement, key: string): void {
const event: KeyboardEvent = new KeyboardEvent('keydown', {
'code': key
});
el.dispatchEvent(event);
}