简体   繁体   English

对使用RxJs主题的Angular2服务进行单元测试

[英]Unit Test a Angular2 service that uses RxJs subjects

In my application I wrote a AuthService to handle backend service authorization. 在我的应用程序中,我编写了AuthService来处理后端服务授权。 To inform components about new login states I use a BehavourSubject that updates its subscribers. 为了通知组件新的登录状态,我使用一个BehavourSubject来更新其订阅者。 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: 现在,我想对该行为进行单元测试,并根据Angular2文档和该故障编写了一个测试,如下所示:

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. 不幸的是,toPromise()从未执行过then()回调。 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). 据我所知,这是因为Observable从未完成(如预期的那样。auth状态可以在整个应用程序生命周期中更改)。 See here . 看这里

Note: login() isn't called because the BehaviourSubject should default to false. 注意:因为BehaviourSubject应该默认为false,所以不会调用login()。 I modified the test to call login() as well. 我修改了测试以调用login()。 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. 我的解决方案是避免使用Angular2测试助手方法。 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. 到目前为止,使用Jasmines done()回调可以达到目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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