In my component, I use router events to display a loader.
I encounter many errors. I guess it's because, on testBed, the component doesn't manage to get real router events.
Error: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?, ?).
TypeError: Cannot read property 'filter' of undefined TypeError:
Cannot read property 'detectChanges' of undefined
How can I "mock" the events to be remove these errors and being able to test my loader method? If not possible, how to make Angular to ignore this part returning him a fake event?
constructor(
private loaderService: LoaderService,
private r: Router
) {
// Listen for router events to trigger the page loader
r.events.
filter(e => this.isStart(e) || this.isEnd(e)).
map(e => this.isStart(e)).
distinctUntilChanged().
subscribe(showLoader => {
if (showLoader) {
this.loaderService.start();
} else {
this.loaderService.complete();
}
});
}
// Router events functions
isStart(e): boolean {
return e instanceof NavigationStart;
}
isEnd(e): boolean {
return e instanceof NavigationEnd ||
e instanceof NavigationCancel ||
e instanceof NavigationError;
}
collectAllEventsForNavigation(obs: Observable<Event>):
Observable<Event[]> {
let observer: Observer<Event[]>;
const events = [];
const sub = obs.subscribe(e => {
events.push(e);
if (this.isEnd(e)) {
observer.next(events);
observer.complete();
}
});
return new Observable<Event[]>(o => observer = o);
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
Component,
RouterLinkStubDirective,
RouterOutletStubComponent
],
providers: [
AppLoaderService,
LoaderService,
Router
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents(); // compile template and css
}));
beforeEach(() => {
fixture = TestBed.createComponent(Component);
comp = fixture.componentInstance;
// trigger initial data binding
fixture.detectChanges();
// find DebugElements with an attached RouterLinkStubDirective
linkDes = fixture.debugElement
.queryAll(By.directive(RouterLinkStubDirective));
// get the attached link directive instances using the DebugElement injectors
links = linkDes
.map(de => de.injector.get(RouterLinkStubDirective) as RouterLinkStubDirective);
});
If I remove from constructor the r.events.[...] code, errors disappear.