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?