Angular单元测试报No provider for ActivatedRouteSnapshot错误如何解决?
错误原因
报错的核心触发点是你在测试的第二个beforeEach钩子中主动调用了TestBed.inject(ActivatedRouteSnapshot):
- 你的组件仅注入了
ActivatedRoute,完全没有用到ActivatedRouteSnapshot,这行注入代码属于冗余逻辑 - 你的测试模块配置中也没有为
ActivatedRouteSnapshot注册对应的提供器,自然会抛出找不到依赖的错误
修复方案
直接删除测试代码里beforeEach函数中的TestBed.inject(ActivatedRouteSnapshot);这一行即可,其余代码无需改动。
如果你后续需要在测试用例中修改路由参数模拟不同场景,可以直接注入你已经配置好的ActivatedRoute模拟对象,示例如下:
// 在测试用例中获取模拟的路由实例 const mockRoute = TestBed.inject(ActivatedRoute); // 修改参数模拟不同场景 mockRoute.snapshot.params.user = 'test_user'; mockRoute.snapshot.params.id = '1001'; // 手动触发变更检测 fixture.detectChanges();
修改后完整可用的测试代码
describe('OKComponent', () => { let component: OKComponent; let fixture: ComponentFixture<OKComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [RouterTestingModule], declarations: [ OKComponent ], providers: [ { provide: ActivatedRoute, useValue: { snapshot: { params: { user: '', id: '' } }, url: of({}) } } ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OKComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
内容的提问来源于stack exchange,提问作者Miomir Dancevic
相关产品推荐
相关产品推荐

