Spying on Router.navigate() in Angular 2 Unit Tests

Mocking Router in Angular2

Posted on February 4, 2017



If your components are changing state using Router.navigate() then you’ll need to mock these out in your unit tests. Here’s how to do it.

1) Import the Router from @angular.

import { Router } from '@angular/router';

2) Add the Router to your providers array and swap it out for a mock router.

TestBed.configureTestingModule ( {
	providers: [
		{ provide: Router, useValue: mockRouter},
} )

3) Finally create mockRouter and create a jasmine spy to watch the navigate method.

let mockRouter = {
	navigate: jasmine.createSpy('navigate')

This will stop your unit test failing when the component can’t find the <router-outlet></router-outlet> element when the test runs.

You can then test that router.navigate() has been called using:

expect (mockRouter.navigate).toHaveBeenCalledWith (['/login']);