Angular单元测试报NullInjectorError无MatSnackBarComponent提供者怎么解决
错误原因
NullInjectorError: R3InjectorError(DynamicTestModule)[MatSnackBarComponent -> MatSnackBarComponent]: NullInjectorError: No provider for MatSnackBarComponent!
出现该错误是因为你的单元测试模块没有配置MatSnackBar相关依赖,MainComponent中用到了自定义MatSnackBarComponent作为SnackBar弹出组件,但TestBed运行时找不到对应的注入配置。
修复方案
推荐优先使用mock依赖的方式做单元测试,隔离非核心依赖,避免引入额外组件的测试成本:
方案1:Mock MatSnackBar服务(推荐)
你只需要在测试模块的providers中添加Mock的MatSnackBar服务,模拟它的核心调用方法即可,无需引入自定义SnackBar组件的依赖:
- 先创建Mock的MatSnackBar实例
- 在providers数组中添加对应的提供者替换真实服务
修改后的完整测试代码如下:
describe('MainComponent', () => { let component: MainComponent; let fixture: ComponentFixture<MainComponent>; let orderService: OrderService; const fakeMatDialogRef = jasmine.createSpyObj(['close']); // 新增mock MatSnackBar对象,模拟你用到的方法即可 const fakeMatSnackBar = jasmine.createSpyObj('MatSnackBar', ['open', 'openFromComponent']); beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ FormsModule, ReactiveFormsModule, HttpClientTestingModule, TranslateModule.forRoot() ], declarations: [MainComponent], providers: [ OrderService, { provide: MatDialogRef, useValue: fakeMatDialogRef }, { provide: MAT_DIALOG_DATA, useValue: {} }, // 新增MatSnackBar的mock提供者 { provide: MatSnackBar, useValue: fakeMatSnackBar } ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(MainComponent); component = fixture.componentInstance; fixture.detectChanges(); }); });
方案2:真实引入SnackBar相关依赖
如果你需要测试和SnackBar交互的真实逻辑,可以按以下步骤配置:
- 在imports数组中添加
MatSnackBarModule - 在declarations数组中添加你的自定义
MatSnackBarComponent - 若
MatSnackBarComponent自身有其他依赖,也要同步在测试模块中添加对应的提供者或mock
注意:CUSTOM_ELEMENTS_SCHEMA只能忽略未知的自定义HTML标签错误,无法解决依赖注入类报错,所以不能通过该配置处理当前问题。
内容的提问来源于stack exchange,提问作者s1auka
相关产品推荐
相关产品推荐

