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();
});
});
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With