title: How to test Angular2's router.navigate?
body: <p>I've run into missing <code>&lt;router-outlet&gt;</code> messages in other unit tests, but just to have a nice isolated example, I created an AuthGuard that checks if a user is logged in for certain actions.</p>
  
  <p>This is the code:</p>
  
  <pre><code>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      if (!this.authService.isLoggedIn()) {
          this.router.navigate(['/login']);
          return false;
      }
      return true;
  }
  </code></pre>
  
  <p>Now I want to write a unit test for this.</p>
  
  <p>This is how I start my test:</p>
  
  <pre><code>beforeEach(() =&gt; {
      TestBed.configureTestingModule({
          imports: [
              RouterTestingModule.withRoutes([
                  {
                      path: 'login',
                      component: DummyComponent
                  }
              ])
          ],
          declarations: [
              DummyComponent
          ],
          providers: [
              AuthGuardService,
              {
                  provide: AuthService,
                  useClass: MockAuthService
              }
          ]
      });
  });
  </code></pre>
  
  <p>I created a DummyComponent that does nothing.
  Now my test. Pretend that the service returns false and that it triggers <code>this.router.navigate(['/login'])</code>:</p>
  
  <pre><code>it('should not let users pass when not logged in', (): void =&gt; {
      expect(authGuardService.canActivate(&lt;any&gt;{}, &lt;any&gt;{})).toBe(false);
  });
  </code></pre>
  
  <p>This will throw an exception with "Cannot find primary outlet to load".
  Obviously I can use <code>toThrow()</code> instead of <code>toBe(false)</code>, but that doesn't seem like a very sensible solution. Since I'm testing a service here, there is no template where I can put the <code>&lt;router-outlet&gt;</code> tag. I could mock the router and make my own navigate function, but then what's the point of RouterTestingModule? Perhaps you even want to check that navigation worked.</p>