title: Angular 5 unit test route with guard
body: <p>I have a route that I need to prevent access from students. I'm trying to write a unit test for this, but it is not working.</p>
  
  <p>My unit tests for the guard itself are working, however when I try to write a test that navigates to /class the canActivate method on the guard does not get called.</p>
  
  <p>Here is the guard:</p>
  
  <pre><code>canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const user = StoreActions.User.getCurrentUser(store.getState());
  
    if(!user) {
      this.router.navigate(['/pages/login']);
      return false;
    }
  
    if(user.username.match(/\d/) !== null) {
      this.router.navigate(['/home']);
      return false;
    }
  
    return true;
  }
  </code></pre>
  
  <p>And the test:</p>
  
  <pre><code>it(
    'should activate guard when a student tries to access /class',
    fakeAsync(
      inject([StudentGuard], (guard: StudentGuard) =&gt; {
        const spy = spyOn(guard, 'canActivate');
        store.dispatch(StoreActions.User.setCurrentUser(TestObjects.User.Student));
        router.navigate(['/class/1']);
        tick();
        expect(spy).toHaveBeenCalled();
        discardPeriodicTasks();
      })
    )
  );
  </code></pre>
  
  <p>Here is the specific route:</p>
  
  <pre><code>{
    path: '',
    children: {
      path: 'class',
      loadChildren: './components/class/class.module#ClassModule',
      canActivate: [StudentGuard]
    }
  }
  </code></pre>
  
  <p>The <code>expect</code> statement fails in the test. However, if I actually impersonate a student and then navigate to /class in the browser the guard works as expected, but it does not activate in the test. How can I make it activate in the test?</p>