How to unit test router.getCurrentNavigation() in Angular?

Viewed 26

I'm struggling to find a way to properly pass some values to my Router in Angular. I have a class that monitors changes in the router navigation to set some variables as follows:

constructor(public route : ActivatedRoute, public router: Router) {
router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
    this.currentRoute = event.urlAfterRedirects;
    this.previousRoute = this.router.getCurrentNavigation().previousNavigation.finalUrl.toString();
    this.setVars();
  }
})}

I managed to find a way to mock the arrival of a new Event as follows (I'm using Karma and Jasmine):

it('should get URL=/home and set currentRoute properly', () => {
  TestBed.get(Router).events.next(new NavigationEnd(0, "/home", "/home"));
  expect(component.currentRoute).toEqual("/home");
});

The above test works just fine, but I can't find a way to test the variable previousRoute. What I tried last is the following approach, trying to mock the method getCurrentNavigation() of the router:

const prev_nav : Navigation = {
  previousNavigation : {
    id: 0,
    initialUrl: null,
    extractedUrl: null,
    finalUrl: { fragment: "", queryParamMap: null, queryParams: null, root: null, toString: () => "/confronto"},
    extras: null,
    previousNavigation: null,
    trigger: "imperative"
  },
  id: 1,
  extractedUrl: null,
  initialUrl: null,
  finalUrl: null,
  extras: null,
  trigger: "imperative"
};

...

it('should call setVars with currentRoute="/home" and set variables properly', () => {
  component.currentRoute = "/home";
  spyOn(TestBed.inject(Router), 'getCurrentNavigation').and.returnValue(prev_nav);
  expect(component.previousRoute).toEqual("/confronto");
});

but it does not seem to work, since I get the error

TypeError: Cannot read properties of null (reading 'previousNavigation')

So the error is definitely in the constructor, because the testing suite is not able to set the value of getCurrentNavigation().

Does anybody have a clue/have encountered a similar problem? Thank you so much in advance to anybody who will be so kind to answer.

0 Answers
Related