How to make material components work with Karma in unit testing Angular
Current technique calls for individual imports of Angular Material modules, as MaterialModule
is deprecated and was removed in 2.0.0-beta.11:
import { MatButtonModule, MatIconModule} from '@angular/material';
Then add the same list as imports in the TestBed config:
beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ ... ], imports: [ MatButtonModule, MatIconModule, ... ], providers: [ ... ] }) .compileComponents();}));
All the providers are provided by calling forRoot()
on the module
imports: [ MaterialModule.forRoot() ]
For versions 2.0.0-beta.4
and later (since the forRoot
method has been removed):
imports: [ MaterialModule ]
For versions 2.0.0-beta.11
and later, since MaterialModule
has been removed, you have to import the modules you require for your test cases yourself:
imports: [ MatButtonModule, MatDialogModule ]
I've been struggling with this as well today and you need to mock out the necessary classes yourself by using providers in jasmine. It's a hassle and I wish there was a better way but at least no more errors...
If anyone has a better idea, please enlighten the rest of the community!
import { async, ComponentFixture, TestBed } from '@angular/core/testing';import { AlertDialogComponent } from './alert-dialog.component';import { MatDialogModule, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';describe('AlertDialogComponent', () => { let component: AlertDialogComponent; let fixture: ComponentFixture<AlertDialogComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [MatDialogModule], declarations: [AlertDialogComponent], providers: [ { provide: MatDialogRef, useValue: {} }, { provide: MAT_DIALOG_DATA, useValue:{} } ], }).compileComponents(); }));