Ned
Ned

Reputation: 236

Unit testing an Angular service with Router dependency: "TypeError: Cannot read property 'navigate' of undefined"

I am trying to test a simple service that uses the Router as a dependency and writes all routes to a history array. I am more or less using the service described on this tutorial.

I have tried all the solutions I could find in the Angular.io documentation. I have tried several solutions here on StackOverflow. I even tried adding routes to mock components, declaring them, and adding those to RouterTestingModule.withRoutes(). For some reason, router is undefined in all cases.

describe('Route State service', () => {
    let routeStateService: RouteStateService;
    let router: Router;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [RouterTestingModule],
            providers: [RouteStateService]
        });

        router = TestBed.get(Router);
        routeStateService = TestBed.get(RouteStateService);
        router.initialNavigation();
    });

    describe('should add each route to history', () => {
        router.navigate(['/test']);
        expect(routeStateService.history.length).toBeGreaterThan(0);
    });

});

The error is fairly straight forward, but for some reason I am unable to get "router" to be defined by normal means. What am I missing?

Upvotes: 0

Views: 1103

Answers (1)

pavan kumar
pavan kumar

Reputation: 823

I think you should be using it in place of describe

it('should add each route to history', () => {
        router.navigate(['/test']);
        expect(routeStateService.history.length).toBeGreaterThan(0);
    });

and also use fakeAsync as the routing is asynchronous

it('navigate to "/test" redirects you to /test', fakeAsync(() => { 
  router.navigate(['/test']); 
  tick(); 
  expect(location.path()).toBe('/test'); 
}));

you can have some reference here https://codecraft.tv/courses/angular/unit-testing/routing/

Upvotes: 1

Related Questions