Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
  });
});
like image 892
orlyohreally Avatar asked Sep 18 '19 08:09

orlyohreally


People also ask

How do you show error in mat form field?

Error messages can be shown under the form field underline by adding mat-error elements inside the form field. Errors are hidden initially and will be displayed on invalid form fields after the user has interacted with the element or the parent form has been submitted.


Video Answer


1 Answers

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

like image 70
RonanCodes Avatar answered Oct 21 '22 04:10

RonanCodes