title: Handling external page redirection on unit testing - jasmine with code coverage
body: <p>writing the unit testing for angular application, login mechanism works on single sing on concept, page will redirect to external url and set the cookie value for the login success (based on cookie setting local storage).</p>
  
  <p>while testing that scenario browser redirects to external page and stops the unit test execution. Currently while doing the unit test commented the redirection and testing the remaining test cases. </p>
  
  <p>While deploying to live again i have to uncomment the redirect code. </p>
  
  <p>How can I handle this scenario in jasmine?</p>
  
  <pre><code>    @Injectable()
  export class AuthGuard implements CanActivate {
      constructor(
          private router: Router,
          private location: Location
      ) { }
  
      canActivate(): boolean {
          if (!localStorage.getItem('API_TOKEN')) {
              this.redirectTOLogin();
              return false;
          } else {
              return true;
          }
      }
  
      redirectTOLogin() {
          window.location.href = environment.appLoginUrl + environment.appUrl;
      }
  }
  </code></pre>
  
  <blockquote>
    <p>spec.ts</p>
  </blockquote>
  
  <pre><code>    describe('Logged in guard should', () =&gt; {
      let loggedInGuard: AuthGuard;
      const router = {
          navigate: jasmine.createSpy('navigate')
      };
  
      // async beforeEach
      beforeEach(async(() =&gt; {
          TestBed.configureTestingModule({
              imports: [FormsModule, CommonModule],
              providers: [AuthGuard, Location, { provide: LocationStrategy, useClass: PathLocationStrategy },
                  { provide: APP_BASE_HREF, useValue: '/' },
                  { provide: Router, useValue: router }
              ]
          })
              .compileComponents(); // compile template and css
      }));
  
      // synchronous beforeEach
      beforeEach(() =&gt; {
          loggedInGuard = TestBed.get(AuthGuard);
      });
  
      it('be able to hit route when user is logged in', () =&gt; {
          localStorage.setItem('API_TOKEN', 'fgsdhfhg4359854dsfsdf#@dfg4545nvnsjfjkh');
          expect(loggedInGuard.canActivate()).toBe(true);
      });
  
      it('not be able to hit route when user is not logged in', () =&gt; {
          localStorage.removeItem('API_TOKEN');
          spyOn(loggedInGuard, 'redirectTOLogin');
          expect(loggedInGuard.redirectTOLogin).toHaveBeenCalled();
      });
  });
  </code></pre>