0

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');
            });
        });
    })));
Ankesh
  • 4,847
  • 4
  • 38
  • 76
  • Why are you using a timeout to inject a router in your service? – Gambo Jul 05 '17 at 07:15
  • There is a circular dependency , which is resolved by using `injector` and `setTimeout`. see this : https://stackoverflow.com/a/41807414/756987 – Ankesh Jul 05 '17 at 08:24

1 Answers1

0

In the Angular documentation they use stubs to swap out the router. Could you not do that?

check out testing/router-stubs.ts here

JGFMK
  • 8,425
  • 4
  • 58
  • 92