Updating input html field from within an Angular 2 test

You’re right that you can’t just set the input, you also need to dispatch the 'input' event. Here is a function I wrote earlier this evening to input text:

function sendInput(text: string) {
  inputElement.value = text;
  inputElement.dispatchEvent(new Event('input'));
  fixture.detectChanges();
  return fixture.whenStable();
}

Here fixture is the ComponentFixture and inputElement is the relevant HTTPInputElement from the fixture’s nativeElement. This returns a promise, so you’ll probably have to resolve it sendInput('whatever').then(...).

In context: https://github.com/textbook/known-for-web/blob/52c8aec4c2699c2f146a33c07786e1e32891c8b6/src/app/actor/actor.component.spec.ts#L134


Update:

We had some issues getting this to work in Angular 2.1, it didn’t like creating a new Event(...), so instead we did:

import { dispatchEvent } from '@angular/platform-browser/testing/browser-util';

...

function sendInput(text: string) {
  inputElement.value = text;
  dispatchEvent(fixture.nativeElement, 'input');
  fixture.detectChanges();
  return fixture.whenStable();
}

Leave a Comment