Reputation: 1126
I have a pair of failing unit tests for compiling my components. In either case, it is due to my code attempting to reference either the router.events
or router.params
:
router.params
ngDoCheck() {
this.route.params.subscribe(
() => {
if (this.router.url !== this.url && this.levelOneState === 'maximized') {
this.levelOneState = 'minimized';
}
this.url = this.router.url;
}
)
}
router.events
this.router.events
.pipe(
find(e => e instanceof NavigationEnd)
)
.subscribe(() => {
this.setCurrentNav();
});
I have set up my test(s) like so:
let router;
router.events = of(new NavigationEnd(0, 'http://localhost:4200/', 'http://localhost:4200/'));
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
...
{ provide: Router, useValue: router }
]
})
.compilecomponents();
}));
However when I run my jasmine tests, I get an error saying that I 'cannot read property 'subscribe' of undefined'. I can't seem to find any answers or guidance to know where I might be going wrong. Can anyone provide some information on how I can set this up differently?
Upvotes: 0
Views: 363
Reputation: 8478
You can create a RouterStub
class and initialize the values to mock Router
in tests.
class RouterStub {
config = [];
events = of({});
params = of({});
url = '';
resetConfig() {}
navigate() { }
}
You can mock the values (url, params etc) as per your use in TestClass.
Use it in the TestBedConfiguration:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
...
{ provide: Router, useValue: new RouterStub()}
]
})
.compilecomponents();
}));
Upvotes: 2