Monday, August 28, 2017

Unit Testing window.keyDown event Angular2 Karma Unit testing

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.


Unit testing an html input in Angular2 Karma Unit Testing

Recently I was working on creating a component, where I needed to unit test my input element.

I tried almost everything to test my input on text element but in vain. Though I have done it many times before with a form control attached to it and it was easy. But this was new...

So just to save you guys some time, below is the code snippet for the same.

test-component.ts:

@Component({
  selector: 'test-component',
  template: '

'
})
class TestComponent {
  name: string;
}

test-component.spec.ts:
Just writing the test case assuming that you know the how to write the test cases in Karma.

inputElement = fixture.debugElement.query(By.css('input')).nativeElement;

it('should set input value programatically', () => {
 
  inputElement.dispatchEvent(new Event('focus'));
  inputElement.value = 'Pratibha';
  inputElement.dispatchEvent(new Event('input'));

  fixture.detectChanges();
  expect(componennt.name).toEqual('Pratibha');
});