Thursday, 29 October 2020

Set form control to dirty in angular test

I have the following component template:

<div>
  <mat-checkbox [(ngModel)]="model.value" required="true" #checkbox="ngModel"></mat-checkbox>
  <mat-error *ngIf="checkbox.invalid && checkbox.dirty">Some Error</mat-error>
</div>

And in my test I would like to test the the error state is shown. However I need to access the input control "#checkbox" in my test and set as dirty.

  it('should show error on invalid', () => {
    const checkbox = fixture.debugElement.query(By.directive(MatCheckbox))
    // I have the mat-checkbox, however not sure how to access the form control to set as dirty
  })

If I add a ViewChild to my component I can access this in the test:

@Component({
  selector: 'my-checkbox',
  templateUrl: './checkbox.component.html',
  styleUrls: ['./checkbox.component.scss']
})
export class CheckboxComponent {
  @Input() model: any;

  // Don't ever use this in production, but added for tests
  @ViewChild('checkbox', { static: false }) checkbox: NgModel;
}

...

// At that point I can access in test through the component
component.checkbox.control.markAsDirty();

However, I would like to access the model inside my test without adding a variable to the component itself as that model is never used.

EDIT: I have also tried to just modify the value to toggle the control to dirty:

it('should show error on invalid', (done) => {
  component.model.value = false  // set value to unchecked
  fixture.detectChanges()

  fixture.whenStable().then(() => {
    const error = fixture.debugElement.query(By.directive(MatError))
    // error is null here, verified that control is not marked as dirty
    done();
  })
})


from Set form control to dirty in angular test

No comments:

Post a Comment