我有以下代码:
class RouterStub {
navigate(url: String) { return url;
}
describe('OwnersComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
OwnersComponent
],
providers: [
{ provide: OwnersService, useClass: OwnersService },
{ provide: Router, useClass: RouterStub }
]
});
TestBed.compileComponents();
});
通过以下测试:
it('navigate when details clicked',
inject([Router], (router: Router) => {
const spy = spyOn(router, 'navigateByUrl');
const navArgs = spy.calls.first().args[0];
const id = comp.owners[0].id;
expect(navArgs).toBe('/owners/detail');
}));
正如您所看到的,即时添加我的路由器并通过注入使用它,但我收到以下错误:
Error: No provider for Router!
如果我没错,inject
使用当前的TestBed注入器,并且组件注入器不提供我的服务,因此它应该正常工作。
我还尝试手动将RouterTestingModule
导入我的TestBed
配置。