The previous example public events = Observable.of( new NavigationEnd(0, 'http://localhost..'));
does not seem to work according to Karma which complains about:
Failed: undefined is not an object (evaluating
'router.routerState.root')
rootRoute@http://localhost:9876/_karma_webpack_/vendor.bundle.js
Despite (mocked) Router instance events' subscription callback has been running successfully in ngOninit()
of original app.component.ts, i.e main application component under testing by Karma:
this.sub = this.router.events.subscribe(e => { // successful execution across Karma
Indeed, the way Router has been mocked sort of looks incomplete, inaccurate as a structure from Karma's prospective: because of router.routerState
that turns out to be undefined at run time.
Here is how Angular Router has been "stubbed" exactly on my side, including RoutesRecognized
events articifically baked as Observable
s in my case:
class MockRouter {
public events = Observable.of(new RoutesRecognized(2 , '/', '/',
createRouterStateSnapshot()));
}
const createRouterStateSnapshot = function () {
const routerStateSnapshot = jasmine.createSpyObj('RouterStateSnapshot',
['toString', 'root']);
routerStateSnapshot.root = jasmine.createSpyObj('root', ['firstChild']);
routerStateSnapshot.root.firstChild.data = {
xxx: false
};
return <RouterStateSnapshot>routerStateSnapshot;
};
to fit what ngOnInit()
body expects, requiring RoutesRecognized
event with deep structure:
ngOnInit() {
this.router.events.filter((event) => {
return event instanceof RoutesRecognized;
}).subscribe((event: RoutesRecognized) => {
// if (!event.state.root.firstChild.data.xxx) {
// RoutesRecognized event... to be baked from specs mocking strategy
});
}
Recap / summary of my <package.json> content:
angular/router: 5.2.9,
karma: 2.0.2,
jasmine-core: 2.6.4,
karma-jasmine: 1.1.2