Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Unit Testing NullInjectorError: R3InjectorError

In my MainComponent I have entryComponent MatSnackBarComponent(custom component). Tests are reporting this error:

NullInjectorError: R3InjectorError(DynamicTestModule)[MatSnackBarComponent -> MatSnackBarComponent]: NullInjectorError: No provider for MatSnackBarComponent!

describe('MainComponent', () => {
  let component: MainComponent;
  let fixture: ComponentFixture<MainComponent>;
  let orderService: OrderService;

  const fakeMatDialogRef = jasmine.createSpyObj(['close']);

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        FormsModule,
        ReactiveFormsModule,
        HttpClientTestingModule,
        TranslateModule.forRoot()
      ],
      declarations: [MainComponent],
      providers: [
        OrderService,
        { provide: MatDialogRef, useValue: fakeMatDialogRef }, 
        { provide: MAT_DIALOG_DATA, useValue: {} }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  }));

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

What should I do to fix this problem?

like image 760
s1auka Avatar asked May 20 '26 23:05

s1auka


2 Answers

Solved. Need to add code below to providers

{ provide: MatSnackBarComponent, useValue: {} }
like image 132
s1auka Avatar answered May 22 '26 11:05

s1auka


You need to add the MatSnackBarModule module in your imports.

imports: [
        FormsModule,
        ReactiveFormsModule,
        HttpClientTestingModule,
        MatSnackBarModule, //<---Added MatSnackBarModule
        TranslateModule.forRoot()
],
like image 30
dom.macs Avatar answered May 22 '26 11:05

dom.macs