测试链接的catchError函数的正确方法是什么

时间:2019-01-19 14:54:49

标签: javascript angular jasmine rxjs

我正在尝试为已经链接了rxjs catchError运算符的@Effect编写一个茉莉花测试,但是正在努力测试第一个catchError之后的可观察对象。

效果如下:

@Effect() submitEndsheets$ = this.actions$.pipe(
    ofType<SubmitEndSheets>(SpreadActionTypes.SUBMIT_ENDSHEETS),
    withLatestFrom(this.store.pipe(select(fromAppStore.fromOrder.getDocumentId))),
    concatMap(([action, documentId]) =>
        this.spreadService.submitEndSheets(documentId).pipe(
            map((response: ActionProcessorDto) => new SubmitEndSheetsSuccess(response.data)),
            catchError((error) => of(undo(action))),
            catchError((error) => of(new MessageModal({
                    message: error.message,
                    title: 'Submission Error!'
                })
            ))
        )
    )
);

和相应的测试:

it('handles errors by sending an undo action', () => {
        const action = {
            type: SpreadActionTypes.SUBMIT_ENDSHEETS,
        };
        const source = cold('a', { a: action });
        const error = new Error('Error occurred!');
        const service = createServiceStub(error);
        const store = createStoreState();
        const effects = new Effects(service, new Actions(source), store);

        const expected = cold('ab', {
           a: undo(action),
            b: new MessageModal({
                message: 'Sorry, something went wrong with your request. Please try again or contact support.',
                title: 'Update Error!'
            }),
        });
        expect(effects.submitEndsheets$).toBeObservable(expected);
    });

供参考,这里是createServiceStub,用于模拟服务,而createStoreState,您猜到了,它创建了模拟存储。

function createServiceStub(response: any) {
    const service = jasmine.createSpyObj('spreadService', [
        'load',
        'update',
        'updateSpreadPosition',
        'submitEndSheets'
    ]);

    const isError = response instanceof Error;
    const serviceResponse = isError ? throwError(response) : of(response);

    service.load.and.returnValue(serviceResponse);
    service.update.and.returnValue(serviceResponse);
    service.updateSpreadPosition.and.returnValue(serviceResponse);
    service.submitEndSheets.and.returnValue(serviceResponse);

    return service;
}

function createStoreState() {
    const store = jasmine.createSpyObj('store', ['pipe']);
    store.pipe.and.returnValue(of({ documentId: 123 }));

    return store;
}

这是测试输出:

FAILED TESTS:
      ✖ handles errors by sending an undo action
        HeadlessChrome 0.0.0 (Mac OS X 10.14.2)
      Expected $.length = 1 to equal 2.
      Expected $[1] = undefined to equal Object({ frame: 10, notification: Notification({ kind: 'N', value: MessageModal({ payload: Object({ message: 'Sorry, something went wrong with your request. Please try again or contact support.', title: 'Update Error!' }), type: 'MESSAGE_MODAL' }), error: undefined, hasValue: true }) }).
          at compare node_modules/jasmine-marbles/bundles/jasmine-marbles.umd.js:389:1)
          at UserContext.<anonymous> src/app/book/store/spread/spread.effects.spec.ts:197:46)
          at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)

在此先感谢您的帮助!

更新catchError可以像这样发送出一系列动作:

@Effect() submitEndsheets$ = this.actions$.pipe(
    ofType<SubmitEndSheets>(SpreadActionTypes.SUBMIT_ENDSHEETS),
    withLatestFrom(this.store.pipe(select(fromAppStore.fromOrder.getDocumentId))),
    concatMap(([action, documentId]) =>
        this.spreadService.submitEndSheets(documentId).pipe(
            map((response: ActionProcessorDto) => new SubmitEndSheetsSuccess(response.data)),
            catchError(error => [
                new PopSingleToast({
                    severity: ToastSeverity.error,
                    summary: 'Failure',
                    detail: `Some error occurred: \n Error: ${error}`
                }),
                undo(action)
            ])
        )
    )
);

相应的测试如下:

it('handles errors by sending an undo action', () => {
        const action = {
            type: SpreadActionTypes.SUBMIT_ENDSHEETS
        };
        const source = cold('a', { a: action });
        const error = new Error('Error occurred!');
        const service = createServiceStub(error);
        const store = createStoreState();
        const effects = new Effects(service, new Actions(source), store);

        const expectedAction = new PopSingleToast({
            severity: ToastSeverity.error,
            summary: 'Failure',
            detail: `Some error occurred: \n Error: ${error}`
        });

        const expected = cold('(ab)', {
            a: expectedAction,
            b: undo(action)
        });

        expect(effects.submitEndsheets$).toBeObservable(expected);
    });

感谢大家的帮助!

1 个答案:

答案 0 :(得分:3)

连续有两个catchErrors意味着第二个将永远不会触发,因为第一个会吃掉错误。

您需要在第一个catchError中重新抛出错误才能进入第二个错误:

catchError(error => throw new Error()),
catchError(error => console.log('now I trigger'))

因此,恐怕您的问题没有什么道理。

相关问题