Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report

0

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'));
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!