Unit test Material Design Components, Material Dialog and Form Builder

April 5, 2021 · 2 min readLucian Ciobanu
Tags:AngularAngularMaterial

As much as I love Angular Material, unit testing it's components can really bug me and they bug me so much that this is my second post on this topic because I've found a much easier way to test them rather than describing each material component with an empty template as I was explaining in a previous post.

The new way I'm doing this is to add "CUSTOM_ELEMENT_SCHEMA" to the testing file as such:

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

[...]
 
 befoareEach(async () => {
   await TestBed.configureTestingModule({
     declarations: [ YourCopmonent ],
     schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
   })
   .compileComponents();
 });

[...]

Also, it is VERY important to add the imported schema to the schemas array.

Another thing I've learned today and hope to remember in the future is that you have to import "ReactiveFormsBuilder" in the testing file when using form builder to generate a form in the component, otherwise you'll get the following error:

NullInjectorError: No provider for FormBuilder!

As for Material Dialog, in the file which tests the component opening the dialog, you should have:

import { MatDialog } from '@angular/material/dialog';

[...]

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [ YourComponent ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
    providers: [
      { provide: MatDialog, useValue: {} }
    ]
  })
  .compileComponents();
});

While in the actual modal testing file, you need to add:

import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog;

[...]
 
beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [ YourModalComponent ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
    providers: [
      { provide: MatDialogRef, useValue: {close: ()=> {}} },
      { provide: MAT_DIALOG_DATA, useValue: {} }
    ]
  })
  .compileComponents();
});

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery