I have a component which is using the Router
in the constructor:
constructor(
private router: Router
) {
router.events.subscribe((event: any) => {
if( event instanceof NavigationEnd ) {
let url: any = event.urlAfterRedirects || event.url;
switch (url) {
case '/login':
case '/forgotPassword':
this.showHeader = false;
break;
default:
this.showHeader = true;
}
}
});
}
The ng2 guide on testing provides an example where it adds a 'spy' just before a method calls navigate().
However, I would like to test the component constructor:
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [HeaderComponent],
providers: [
{ provide: Router, useClass: FakeRouter },
{ provide: AuthService, useClass: null }
]
});
});
it('should be visible on /login', inject([Router], (router: Router) => {
let routerEventSpy = spyOn(router, 'events')
.and.returnValue(Observable.of(new NavigationEnd(1, '/login', '/login')));
debugger;
let fixture = TestBed.createComponent(HeaderComponent);
}));
I thought that since Router
is a singleton, if I add a spy to it in the test, and then call TestBed.createComponent
which constructs the component, the component would find the spy already attached. However this isn't the case; I get :
TypeError: Cannot read property 'subscribe' of undefined
How can I attach a spy before the construction of the component, bearing in mind that I might want to construct the component multiple times for multiple tests.
Aucun commentaire:
Enregistrer un commentaire