ERROR NullInjectorError: R3InjectorError(DynamicTestModule)[KDSDialogService -> MatDialog -> MatDialog]: NullInjectorError: No provider for MatDialog

Viewed 1869

I'm doing unit testing on my application. I'm new to testing, so I need your help.

In my application I make a service that uses MatDialog ( KDSDialogService). I've tried putting many import alternatives, my service or matdialog as providers I have no idea what to do

export declare class KDSDialogService {
    dialog: MatDialog;
    private dialogRef;
    constructor(dialog: MatDialog);
    open(componentOrTemplateRef: ComponentType<any> | TemplateRef<any>, title?: string, data?: any, size?: DialogSize, showClose?: boolean): MatDialogRef<any, any>;
    static ɵfac: ɵngcc0.ɵɵFactoryDef<KDSDialogService, never>;
}

And in my home.component.spec I import and make the declarations here, but I still get this error.

describe('HomeComponent', () => {
   let component: HomeComponent;
   let fixture: ComponentFixture<HomeComponent>;

   beforeEach(async(() => {
      TestBed.configureTestingModule({
         declarations: [HomeComponent ],
         imports:[KDSDialogService, MatDialogModule],
  
      }).compileComponents();
   }));

   beforeEach(() => {
      fixture = TestBed.createComponent(HomeComponent);
      component = fixture.componentInstance;
    
   });

   it('should create', () => {
      fixture.detectChanges();
      expect(component).toBeTruthy();
   });
});

Print of the error

1 Answers

You can mock it like this:

import { MatDialog } from '@angular/material/dialog';
//...
    let matDialogService: jasmine.SpyObj<MatDialog>;
    matDialogService = jasmine.createSpyObj<MatDialog>('MatDialog', ['open']);

    TestBed.configureTestingModule({
      providers: [
        {
          provide: MatDialog,
          useValue: matDialogService,
        },

Related