具有可观察的.catch块的角度测试方法

时间:2017-08-02 20:52:23

标签: angular unit-testing rxjs rxjs5

我是RxJS世界的新手,我的单元测试有问题。

在我的Angular组件中,我有一个login方法 - 我只是从服务中调用方法。服务内部的方法返回Observable到组件。在这里你可以看到一段代码:

public login(username: string, password: string): void{
    this.authService.login(username, password) //this return Observable in real world
            .catch(() => {
                this.formErrors['general.error'] = true;
                return Observable.throw('error! :<');
            })
            .subscribe(() => {
                this.router.navigate(['/someRoute']);
            });
}

正如你所看到的那样,它是一种非常简单的方法(在实际应用中它会变得更复杂,但现在并不重要)现在我正在尝试编写一个单元测试(在Jasmine):

    it('', () => {
        authService.login.and.returnValue(Observable.throw('')); //authService is my mock
        component.login('u', 'p');
        expect(component.formErrors['general.error']).toBeTruthy();
    });

但是我收到错误,因为我从catch部分抛出了错误: login.component login FAILED (error! :< thrown)

我做错了什么?

P.S。 我试图添加expect(component.login).toThrow();,但没有成功......

1 个答案:

答案 0 :(得分:2)

不要直接调用component.login('u', 'p'),而是让测试运行者去做。

it('', () => {
    authService.login.and.returnValue(Observable.throw('')); //authService is my mock

    expect(component.login.bind(component, 'u', 'p')).toThrow(...);
    expect(component.formErrors['general.error']).toBeTruthy();
});
相关问题