3

I'm trying to write a unit test in Angular 4.3.6.

I have already looked at the following references:

  1. how can i create MockActivatedRoute for the parent routes of ActivatedRoute in angular 4 Unit testing

  2. How to mock an activatedRoute parent Route in angular2 for testing purposes?

  3. Testing Angular 2 parent route

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?

DAG
  • 2,460
  • 5
  • 33
  • 61
  • 1
    if you will mock `ActivatedRoute` then you have to pass or create all possible value `ActivatedRoute` uses in your test. – Aniruddha Das Aug 29 '17 at 15:29
  • As @AniruddhaDas said. Basic params: https://stackoverflow.com/questions/38356084/how-to-unit-test-a-component-that-depends-on-parameters-from-activatedroute. Parent params: https://stackoverflow.com/questions/40789637/how-to-mock-an-activatedroute-parent-route-in-angular2-for-testing-purposes – Z. Bagley Aug 29 '17 at 15:34
  • I did this already, but my subscription does not get called, I thought it was because of the mock – DAG Aug 29 '17 at 15:36

0 Answers0