Chandra
Chandra

Reputation: 505

How do I trigger a keyup/keydown event in an angularjs unit test?

I want to unit test a directive that emulates a placeholder, where the input value is cleared only on keyup/down events.

Upvotes: 37

Views: 55431

Answers (6)

Anandharajan j
Anandharajan j

Reputation: 1

it('should call listenToModalCloseEvent', fakeAsync(() => {
  spyOn(component, 'closeDropDownMenu').and.callThrough();
  const keyboardEvent = new KeyboardEvent('keydown', {
    'key': 'Escape'
  });
  document.dispatchEvent(keyboardEvent);
  fixture.detectChanges();
  expect(component.closeDropDownMenu).toHaveBeenCalled();
}));

Upvotes: 0

akcasoy
akcasoy

Reputation: 7215

I recently wanted to test this HostListener on a component (Angular 2):

  @HostListener('keydown.esc') onEsc() {
    this.componentCloseFn();
  };

And after searching for some time, this is working:

..
nativeElement.dispatchEvent(new KeyboardEvent('keydown', {'key': 'Escape'}));
...

Upvotes: 2

artronics
artronics

Reputation: 1496

if you are using angular2, you can trigger any event by calling dispatchEvent(new Event('mousedown')) on HTMLElement instance. for example: Tested with angular 2.rc1

it('should ...', async(inject([TestComponentBuilder], (tcb:TestComponentBuilder) => {
return tcb.createAsync(TestComponent).then((fixture: ComponentFixture<any>) => {
  fixture.detectChanges();

  let com = fixture.componentInstance;

  /* query your component to select element*/
  let div:HTMLElement = fixture.nativeElement.querySelector('div');

 /* If you want to test @output you can subscribe to its event*/
  com.resizeTest.subscribe((x:any)=>{
    expect(x).toBe('someValue');
  });
  /* If you want to test some component internal you can register an event listener*/
  div.addEventListener('click',(x)=>{
    expect(x).toBe('someOtherValue');
  });
  /* if you want to trigger an event on selected HTMLElement*/
  div.dispatchEvent(new Event('mousedown'));
  /* For click events you can use this short form*/
  div.click();

  fixture.detectChanges();
});

Upvotes: 3

kevswanberg
kevswanberg

Reputation: 2109

I got something like this working.

element.triggerHandler({type:"keydown", which:keyCode});

Upvotes: 9

Maciej Dzikowicki
Maciej Dzikowicki

Reputation: 887

I had issues with using accepted answer. I found other soultion.

var e = new window.KeyboardEvent('keydown', {
  bubbles: true,
  cancelable: true,
  shiftKey: true
});

delete e.keyCode;
Object.defineProperty(e, 'keyCode', {'value': 27});

$document[0].dispatchEvent(e);

Working example can be found here

Upvotes: 14

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

You need to create an event programatically and trigger it. To do so including jQuery for unit tests is quite useful. For example, you could write a simple utility like this:

  var triggerKeyDown = function (element, keyCode) {
    var e = $.Event("keydown");
    e.which = keyCode;
    element.trigger(e);
  };

and then use it in your unit test like so:

triggerKeyDown(element, 13);

You can see this technique in action in the http://angular-ui.github.io/bootstrap/ project here: https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/test/typeahead.spec.js

Disclaimer: let's be precise here: I'm not advocating using jQuery with AngularJS! I'm just saying that it is a useful DOM manipulation utility for writing tests interacting with the DOM.

To make the above code work without jQuery, change:

$.Event('keydown')

to:

angular.element.Event('keydown')

Upvotes: 35

Related Questions