Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate a key up Event from an input in an Angular -cli 4 unit test

In vanilla JS you can simulate a key up on an input by doing:

testComponent.dispatchEvent(new Event("keyup"))

However doing this in the angular-cli unit test or in the console doesn't trigger this function in my component, which responds to key events by:

  @HostListener('keyup', ['$event'])
  onKeyUp(event: KeyboardEvent) {

Any ideas?

like image 580
Nikos Avatar asked Mar 09 '17 11:03

Nikos


People also ask

What is the correct way to trigger a click event on a button when testing an Angular component?

For click event we can use triggerEventHandler method of Angular DebugElement class. We can also call native JavaScript click method of button. On click of button, we call a component method and it is possible that our component method has other dependencies to execute.

How do you mock a component in Angular unit testing?

A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.

What the describe keyword is used for in Angular unit testing?

The describe code block represents the test suite for AppComponent. It contains specs and additional code that's used for testing AppComponent. beforeEach is a global function in Jasmine that runs some setup code before each spec in the test suite.

How do you trigger event in Jasmine?

According to the Angular Testing documentation, to trigger the events from the tests, we use the triggerEventHandler() method on the debug element. This method takes the event name and the object .


1 Answers

You should create an event

const event = new KeyboardEvent('keyup', {
      bubbles : true, cancelable : true, shiftKey : false
});

And then get the reference of the debugElement using css selector

const input = debugElement.query(By.css('#id_of_element'));

And then reference of native html element from the previous one

const inputElement = input.nativeElement;

Assign the value for the native element as , now the text field value contains 12.

inputElement.value = 12;

finally dispatch the key up event

inputElement.dispatchEvent(event);

it will trigger the function

Dont forget to add the following line in before each and make sure you define debugElement

debugElement = fixture.debugElement;

Hope it helps

like image 72
Tharzeez Avatar answered Sep 19 '22 17:09

Tharzeez