0

I am having trouble with creating unit test for an Angular directive. The problem is that after setting inputEl.value and call input.dispatchEvent(new Event('input')) then fixture.detectChanges(), input value is deleted and will be an empty string (so all in all I am not even getting there to test the directive).

Here is my code:

@Component({
  template: `
  <form [formGroup]="formGroup">
    <input formControlName="datepicker">
  </form>`
})
class TestComponent implements OnInit {
  formGroup!: FormGroup;

  constructor(private readonly formBuilder: FormBuilder) { }

  ngOnInit() {
    this.initForm();
  }

  initForm() {
    this.formGroup = this.formBuilder.group({
      datepicker: ['']
    })
  }
}


...
  beforeEach(() => {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  })

it('should add 23:59:59 sec to the initial date', async () => {
    component.ngOnInit();
    fixture.detectChanges();

    const debugEl: HTMLElement = fixture.debugElement.nativeElement;
    const inputEl: HTMLInputElement | null = debugEl.querySelector('input');
    const value = 'test';

    if(inputEl) {
      inputEl.value = value;
      inputEl.dispatchEvent(new Event('input'));
      fixture.detectChanges();
      expect(inputEl.value).toBe(value);
    }
});

Result: Error: Expected '' to be 'test'.

What am I doing wrong here?

balintd
  • 93
  • 7
  • 1
    Not 100% sure, but I think invalid date strings are ignored on inputs of type date and thus made empty string. Try "2020-02-06" instead of test – Michael Feb 06 '20 at 11:47
  • Well date type was not given to the input field, however after changing to date it's working. (and now it's also working with value 'test'. Been stucking with the issue for hours... thanks! – balintd Feb 06 '20 at 11:55

0 Answers0