rxjs模拟响应到管道/点击

时间:2019-02-06 15:32:03

标签: javascript angular unit-testing rxjs karma-jasmine

我正在为Angular 7.1应用程序进行单元测试。我们使用rxjs 6.3.3。我的组件有一个如下所示的服务调用。

this.registrationservice
            .createAccount(model)
            .pipe(
                tap(
                    (resp: {}) => {
                        this.router.navigate([url]);
                    },
                    (error: any) => {
                        this.isError = true;
                        this.registrationState.resetData();
                        this.resetUrl = this.registrationState.verifyStepState(RegistrationStepName.confirm);
                    }
                ),
                finalize(() => {
                    this.isLoading = false;
                })
            )
            .subscribe();

当我尝试返回错误响应时,它永远不会进入.tap错误处理程序?我该如何模拟呢?这是我的考试

it("Register User error", fakeAsync(() => {
        let errorResponse = {
            statusCode: "400",
            error: "no good"
        };
        userRegisterSvcStub.createAccount.and.throwError(ErrorObservable.create(errorResponse));
        let model = new UserRegisterModel({ userregistrationtypeid: modelProviderType.id, ...modelNpi, ...modelCreateAccount });
        registerDataStateSpy.getRegisterUserData.and.returnValue(model);
        registerDataStateSpy.verifyStepState.and.returnValue("../beginning");
        component.ngOnInit();
        tick();
        expect(mockRouter.navigate).not.toHaveBeenCalled();
        expect(component.resetUrl).toEqual("../beginning");
    }));

2 个答案:

答案 0 :(得分:0)

您可以使用rxjs中的throwError运算符创建一个Observable,该对象立即抛出传递给函数的所有内容。

答案 1 :(得分:0)

为克里斯蒂安的答案提供更多细节...

从您的使用方式来看,我假设userRegisterSvcStub是一个间谍对象,而createAccount()是对该对象的间谍方法?如果是这样,那么您当前在此处使用的代码:

userRegisterSvcStub.createAccount.and.throwError(ErrorObservable.create(errorResponse));

实际上将使用here中所述的茉莉花throwError()方法引发错误。

我想您想要的是使用Christian建议的rxjs throwError。为此,您的代码将如下所示:

import { throwError } from 'rxjs'; // up with your other imports

userRegisterSvcStub.createAccount.and.returnValue(throwError(errorResponse));

我希望这会有所帮助。