Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

150
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda