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?
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
I my case somehow value was empty to I had to explicitly define it:
function generateKeyUpEvent(value: string): KeyboardEvent {
const event: KeyboardEvent = new KeyboardEvent('keyup', { bubbles: true, cancelable: true });
Object.defineProperty(event, 'target', { value: { value } });
return event;
}
and then despatch in my test case:
component.input.nativeElement.dispatchEvent(generateKeyUpEvent('a'));