0

I'm testing a service (myService) in Angular 2 that has a dependency on Router. Since I'm using one of Angular's components, I'm going to use Angular's TestBed class. So I set up my beforeEach as follows:

let router: Router;
beforeEach(async(() => {
        TestBed.configureTestingModule({
            providers: [
                {provide: Router, useClass: RouterStub}
            ]
        });
        router = TestBed.get(Router);
        myService = new MyService(router);
    }));

where RouterStub is defined as

@Injectable()
export class RouterStub {
    navigate() {};
}

Now I write my test to fail (red, green, refactor... )

it('on myServiceMethod calls router', () => {    
    let spy = spyOn(router, 'navigate');

    // myService.myServiceMethod(); // commented out so test fails

    expect(spy).toHaveBeenCalledTimes(1);
})

and the test fails as expected. However, I now try and write the same test using the TestBed Inject function, i.e.,

it('on myServiceMethod calls router', () => {
    inject([Router], (router: Router) => {
        let spy = spyOn(router, 'navigate');

       // myService.myServiceMethod(); // commented out so test fails

        expect(spy).toHaveBeenCalledTimes(1);
    })   
})

and this test passes even though I thought the Inject function would retrieve the same instance of Router from the TestBed. What am I not understanding?

James B
  • 8,975
  • 13
  • 45
  • 83
  • Have you tried with `RouterModule.forRoot()` in your `TestBed`?, Router service won't be injected if you don't call `forRoot()`. But it's just a long shoot. – dlcardozo Mar 05 '17 at 18:22
  • @camaron Good thought, but unfortunately doesn't fix it. Seems odd this, and can only assume I'm missing something. – James B Mar 05 '17 at 18:30

1 Answers1

0

Mate it you should use getTestBed from @angular/core/testing and inject it like,

  getTestBed().get(YourService)
Babar Hussain
  • 2,917
  • 1
  • 17
  • 14
  • But isn't that what I'm doing in the first test that passes? Yes, this works and is what I'm currently using, but the question is more about understanding the `inject` function. – James B Mar 05 '17 at 19:00