Search code examples
angularunit-testingkarma-jasmineangular-material-7

How to test that component template contains mat-error


I want to create test for component that checks that mat-error is displayed.

I've created a test but it's failing because DOM does not have mat-error at all during testing. Although it works fine when project is served.

Template snippet

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

Test set up

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

Solution

  • tldr; You have to touch the FormControl before any errors will show.


    You have to first touch the component.
    Using reactive forms (where nameFormControl is of type FormControl):

    component.nameFormControl.markAsTouched();
    

    Your mat-error element will now show in the view.


    For a real scenario you will have an ngIf on the mat-error element and will need to set that error as well.

    Example template:

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

    Adding error:

    component.nameFormControl.setErrors({ required: true} as ValidationErrors);
    

    Similar issue for this question:
    How to catch the <mat-error> error message text content using Protractor

    Official docs on Angular Form Validation:
    https://angular.io/guide/form-validation#why-check-dirty-and-touched