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

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

Posted by: admin November 17, 2017 Leave a comment

Questions:

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

Answers:

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')

Questions:
Answers:

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

Questions:
Answers:

I got something like this working.

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

Questions:
Answers:

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();
});

Leave a Reply

Your email address will not be published. Required fields are marked *