I've recently implemented a change function that I'm passing to the change event for a dynamic form control. This function evaluates the control's state of modification (dirty) and checks for any errors. Based on this evaluation, a boolean flag is set to true or false. The value of this flag determines whether an error message is displayed within a <div>
element. Everything seems to be working smoothly when tested in the browser. However, there seems to be an issue with setting the "dirty" state during unit testing. Below is a snippet of my code:
HTML
<form [formGroup]="myForm" novalidate>
<input id="age" formControlName="age" (change)="onChange()" />
<div id="ageError" *ngIf="ageIsError()">
<label>Age has errored</label>
</div>
</form>
Component
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
age: [null, [Validators.min(18)]]
});
}
onChange() {
if (this.ageIsError())
// do something
}
ageIsError() {
return this.myForm.controls.age.hasError('min') &&
this.myForm.controls.age.dirty;
}
Unit Test
it('should display error message when age is less than 18', fakeAsync(() => {
let age = component.myForm.controls.age;
age.setValue('10', { emitEvent: true });
fixture.detectChanges();
fixture.whenStable().then(() => {
let ageError = debugElement.query(By.css('#ageError')).nativeElement;
expect(component.ageIsError()).toBe(true);
expect(ageError.innerText).toContain('Age has errored');
});
}));
While the implementation works fine in the browser, the unit test is failing due to issues with emitting the event in Jasmine to set the control to a dirty state. If anyone has suggestions on how to resolve this issue or achieve the desired outcome more efficiently, please share your insights. Thank you!