在 angular 测试中将表单控件设置为脏

Set form control to dirty in angular test

我有以下组件模板:

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

在我的测试中,我想测试显示的错误状态。但是我需要在我的测试中访问输入控件“#checkbox”并将其设置为脏。

      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
      })

如果我将 ViewChild 添加到我的组件,我可以在测试中访问它:

    @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();

但是,我想在我的测试中访问模型而不向组件本身添加变量,因为该模型从未被使用过。

编辑:我还尝试修改值以将控件切换为脏:

    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();
      })
    })

我能够抓取模型如下:

const model = fixture.debugElement.query(By.directive(MatCheckbox)).references['checkbox']

然后标记为脏

model.control.markAsDirty()

你不能直接使用特定控件本身的 Id 检查 fixture.debugElement.query(By.css("#id")).markAsDirty()