Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

158
Visualizações
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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

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

over 4 years ago · Santiago Trujillo Relatório

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'));
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda