Dispatch Event with a target.value in Jasmine

Viewed 1411

How do I dispatch a change Event in a Jasmine unit test that includes a target.value?

The component under test has a method like this:

@HostListener('change', ['$event'])
onChange(event) {
  const value = event.target.value;
  this.value = value;
}

See the TODO in my current unit test draft. I need to include the target.value when dispatching the event, but the Event interface does not seem to contain a target property.

scenarios.forEach((scenario) => {
  it(`changing control value should result in correct value ${scenario.condition}`, fakeAsync(() => {
    // arrange
    component.writeValue(scenario.writtenControlValue);

    // act
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      const input = fixture.debugElement.query(By.css('input')).nativeElement;
      input.value = scenario.newControlValue;
      input.dispatchEvent(new Event('change')); // TODO: pass scenario.newControlValue to Event's target.value

      // assert
      expect(component.value).toEqual(scenario.expectedResult);
    });
  }));
});
1 Answers

Check out this link, maybe you can use triggerEventHandler.

scenarios.forEach((scenario) => {
  it(`changing control value should result in correct value ${scenario.condition}`, fakeAsync(() => {
    // arrange
    component.writeValue(scenario.writtenControlValue);

    // act
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      const input = fixture.debugElement.query(By.css('input'));
      input.nativeElement.value = scenario.newControlValue;
      input.triggerEventHandler('change', { target: input.nativeElement });


      // assert
      expect(component.value).toEqual(scenario.expectedResult);
    });
  }));
});

I also use this link as a guide

Related