How do I add svg files via MatIconRegistry in unit tests?

Just spent a couple hours on this. It looks like Angular now provides a FakeMatIconRegistry. It squashed about 90% of the karma warnings, but still a few remain...

Had to do a lot of this:

TestBed.configureTestingModule({
    declarations: [ MyComponent ],
    imports: [
        ...
        MatIconModule,
    ],
    providers: [
        ...
        { provide: MatIconRegistry, useClass: FakeMatIconRegistry }
    ]
}).compileComponents();

Mock the mat-icon selector with the following component at the top of the unit test

@Component({
    selector: 'mat-icon',
    template: '<span></span>'
})
class MockMatIconComponent {
    @Input() svgIcon: any;
    @Input() fontSet: any;
    @Input() fontIcon: any;
}

Then override the MatIconModule in the unit test as follows

beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [ ...],
        providers: [ ...  ],
        imports: [ MatIconModule, NoopAnimationsModule ]
    })
    .overrideModule(MatIconModule, {
    remove: {
       declarations: [MatIcon],
       exports: [MatIcon]
    },
    add: {
        declarations: [MockMatIconComponent],
        exports: [MockMatIconComponent]
   }
   })
  .compileComponents();

You will no longer have the 'Error retrieving icon: Unable to find icon with the name ":myIcon"' issue when running the unit tests


can just do:

...
import { MatIcon } from '@angular/material/icon';
import { MatIconTestingModule } from '@angular/material/icon/testing';

describe('MyComponent', () => {
  ...

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent, MatIcon],
      imports: [MatIconTestingModule],
    }).compileComponents();
  }));

...

});

This will generate a test icon rendering without the http request