简体   繁体   中英

Unit Test a Angular2 service that uses RxJs subjects

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:

@Injectable()
export class OAuth2Service {

    private authState: BehaviorSubject<boolean> = new BehaviorSubject(false);

    login(): void {
        this.authState.next(true);
    }

    public getAuthState(): Observable<boolean> {
        return this.authState.asObservable();
    }
}

Now, I want to unit test that behaviour, and wrote a test according to the Angular2 doc and that Ticket as follows:

it('should handle auth state', async(inject([OAuth2Service, TokenDao], (oAuth2Service: OAuth2Service, tokenDao: TokenDao) => {

    return oAuth2Service.getAuthState().toPromise()
        .then((state) => {
            expect(state).toEqual(false);
        });
    })
));

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). See here .

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.

The Question: How to unit test the behaviour of my auth service properly? Did I miss something?

My solution was to avoid the Angular2 test helper methods. So I refactored the test to:

it('should handle auth state', (done) => {
    let oAuth2Service: OAuth2Service = TestBed.get(OAuth2Service);
    oAuth2Service.getAuthState().subscribe((state) => {
        expect(state).toEqual(false);
        done();
    });
});

Using Jasmines done() callback did the trick so far.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM