I'm trying to write a unit test in Angular 4.3.6.
I have already looked at the following references:
Thing is - I don't think (I might be completely wrong) I should mock ActivatedRoute in this scenario, for example:
I have a children component which has a subscribe to a parent activated route, like that:
// children.component.ts
ngOnInit() {
this.activatedRoute.parent.paramMap
.map(m => m.get("contractId"))
.distinctUntilChanged()
.subscribe(contractId => {
console.log(contractId);
});
}
Now I want to write the following test:
should call the parent subscription when contractId changes
I thought something like that:
it("should call the parent subscription when contractId changes", fakeAsync(() => {
// Initializes route with contractId 1000
router.navigate(["1000", "Parent", "Children"]);
tick();
fixture.detectChanges(); // this calls ngOnInit
// changes the contractId to 2000
router.navigate(["2000", "Parent", "Children"]);
tick();
expect(component.contractId).toBe("2000");
}));
I get the following error:
TypeError: Cannot read property 'paramMap' of null
I published a plunker for that: https://plnkr.co/edit/2SXzvSDe3OiwvvRJYXfN?p=preview
Note that in the plunker I wrote two tests. The first one is running just fine, so the router is working.
How can I watch for changes in the route in the unit test and why is parent null?
EDIT:
I updated my plunker with the mocked ActivatedRoute based on ActivatedRouteStub. Then now I get the following error:
TypeError: Cannot read property 'paramMap' of undefined
That is probably because the stub does not define parent, consequently it's undefined.
I could define a parent property in the mock, but would this be correct?