title: Unit Test a Angular2 service that uses RxJs subjects
body: <p>In my application I wrote a AuthService to handle backend service authorization. To inform components about new login states I use a BehavourSubject that updates its subscribers. Here is the (simplified) code:</p>
  
  <pre><code>@Injectable()
  export class OAuth2Service {
  
      private authState: BehaviorSubject&lt;boolean&gt; = new BehaviorSubject(false);
  
      login(): void {
          this.authState.next(true);
      }
  
      public getAuthState(): Observable&lt;boolean&gt; {
          return this.authState.asObservable();
      }
  }
  </code></pre>
  
  <p>Now, I want to unit test that behaviour, and wrote a test according to the Angular2 doc and that <a href="https://github.com/angular/angular/issues/4715#issuecomment-149288405" rel="nofollow noreferrer">Ticket</a> as follows:</p>
  
  <pre><code>it('should handle auth state', async(inject([OAuth2Service, TokenDao], (oAuth2Service: OAuth2Service, tokenDao: TokenDao) =&gt; {
  
      return oAuth2Service.getAuthState().toPromise()
          .then((state) =&gt; {
              expect(state).toEqual(false);
          });
      })
  ));
  </code></pre>
  
  <p>Unfortunately, the toPromise() is never executing its then() callback. As far as I could figure out, it's because the Observable never gets completed (As intended. The auth state can change during the whole app lifecycle). <a href="https://github.com/Reactive-Extensions/RxJS/issues/1088" rel="nofollow noreferrer">See here</a>.</p>
  
  <p><em>Note: login() isn't called because the BehaviourSubject should default to false. I modified the test to call login() as well. Still no promise callback.</em></p>
  
  <p><strong>The Question:</strong> How to unit test the behaviour of my auth service properly? Did I miss something?</p>