I have a service in which has some dependency injected using the Injector
(I have inherited this code and cant change the initialization for now) using 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);
}
}
I need to test myMethod
but when Ever I test this the setTimeout
is called after the TestInExecution-> mymethod
is called and gives an error
TypeError: Cannot read property 'url' of undefined
as Router
is not instantiated.
How to make sure that the router is injected properly before executing the test.
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');
});
});
})));