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?