Angular Unit-testing NullInjectorError: R3InjectorError(DynamicTestModule)[MatSnackBarComponent -> MatSnackBarComponent]:

Angular Unit-testing NullInjectorError: R3InjectorError(DynamicTestModule)[MatSnackBarComponent -> MatSnackBarComponent]:

在我的 MainComponent 中,我有 entryComponent MatSnackBarComponent(自定义组件)。 当我写测试时,我得到这个错误:

NullInjectorError: R3InjectorError(DynamicTestModule)[MatSnackBarComponent -> MatSnackBarComponent]: NullInjectorError:没有 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();
  });

我应该怎么做才能解决这个问题?

您需要在导入中添加 MatSnackBarModule 模块。

imports: [
        FormsModule,
        ReactiveFormsModule,
        HttpClientTestingModule,
        MatSnackBarModule, //<---Added MatSnackBarModule
        TranslateModule.forRoot()
],

已解决。需要将下面的代码添加到 providers

{ provide: MatSnackBarComponent, useValue: {} }