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

标签 angular unit-testing karma-jasmine angular-material-7

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

我创建了一个测试,但它失败了,因为 DOM 在测试期间根本没有 mat-error。尽管在提供项目时它工作正常。

模板片段

<mat-error>
    Error message
</mat-error>

测试设置
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();
  });
});

最佳答案

tldr;在显示任何错误之前,您必须触摸 FormControl

您必须先触摸组件。
使用 react 形式(其中 nameFormControlFormControl 类型):

component.nameFormControl.markAsTouched();

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

对于实际情况,您将在 ngIf 元素上有一个 mat-error 并且还需要设置该错误。

示例模板:

<mat-error *ngIf="nameFormControl.hasError('required')">
    Error message
</mat-error>

添加错误:
component.nameFormControl.setErrors({ required: true} as ValidationErrors);

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

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

关于angular - 如何测试该组件模板包含 mat-error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57988530/

相关文章:

npm - 包 rxjs@5.0.0-beta.6 不满足其 sibling 的 peerDependencies 要求?

unit-testing - 以预定义的顺序执行测试用例

javascript - 单元测试 Javascript 匿名函数

angular - 如何为 Angular react 形式的自定义验证器编写单元测试用例?

javascript - Angular 2 中的 ng 重复

angular - 通过按 Ctrl 键并选择每一行来选择表中的多行。我如何将其应用到 Angular 2 上

python - 从 Nose2 插件跳过单元测试

javascript - AngularJS:类型错误:未定义不是本地存储的对象

angularjs - 尝试测试工厂时遇到注入(inject)问题

angular - 在特征内选择数据的 ngrx/entity 问题