我有一个服务,其中使用Injector
注入了一些依赖项(我已经继承了此代码,暂时无法更改初始化),使用setTimeout
@Injectable
export class MyService {
router:Router;
constructor(private injector: Injector) {
setTimeout(() => {
debugger;
this.router = injector.get(Router);
});
}
public myMethod(){
const someString = this.router.url.slice(1,someLength);
}
}
我需要测试myMethod
但是当我测试这个时,调用setTimeout
后调用TestInExecution-> mymethod
并出错
TypeError: Cannot read property 'url' of undefined
因为Router
未实例化。
如何确保在执行测试之前正确注入路由器。
fit('Test My Service', fakeAsync(inject([Router, Location, MyService],
(_router: Router, _location: Location, myService: MyService) => {
let fixture = TestBed.createComponent(SomeComponent);
//Wait for component to Initialize
tick(500);
fixture.detectChanges();
fixture.whenStable().then(() => {
_router.navigate(['/someCompoenet']).then(() => {
expect(myService.myMethod()).toBe('Some String');
});
});
})));