如何测试组件模板包含 mat-error

orl*_*lly 8 unit-testing karma-jasmine angular angular-material-7

我想为组件创建测试来检查是否显示 mat-error。

我已经创建了一个测试,但它失败了,因为 DOM 在测试过程中根本没有 mat-error 。尽管在项目提供服务时它工作得很好。

模板片段

<mat-error>
    Error message
</mat-error>
Run Code Online (Sandbox Code Playgroud)

测试设置

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        MatFormFieldModule,
        ReactiveFormsModule,
        MatInputModule,
        MatFormFieldModule,
        BrowserAnimationsModule
      ],
      declarations: [MyComponent]
    }).compileComponents();
  }));

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

  fit('should display error', () => {
    const matErrorEl: HTMLElement = 
    fixture.debugElement.query(By.directive(MatError)).nativeElement;
    expect(matErrorEl).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

RoR*_*oRo 9

太棒了;您必须FormControl先触摸 ,然后才会显示任何错误。


您必须先触摸该组件。
使用反应形式(其中nameFormControl是 类型FormControl):

component.nameFormControl.markAsTouched();
Run Code Online (Sandbox Code Playgroud)

您的mat-error元素现在将显示在视图中。


对于真实场景,您将有一个ngIfonmat-error元素,并且还需要设置该错误。

示例模板:

component.nameFormControl.markAsTouched();
Run Code Online (Sandbox Code Playgroud)

添加错误:

component.nameFormControl.setErrors({ required: true} as ValidationErrors);
Run Code Online (Sandbox Code Playgroud)

此问题的类似问题:
How to catch the <mat-error> error message text content using Protractor

有关 Angular 表单验证的官方文档:
https://angular.io/guide/form-validation#why-check-dirty-and-touched