簡體   English   中英

什么是測試鏈接的catchError函數的正確方法

[英]What is the correct way of testing chained catchError functions

我正在嘗試為已鏈接rxjs catchError運算符的@Effect編寫茉莉花測試,但正在努力測試除第一個catchError之外的任何可觀察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);
    });

感謝大家的幫助!

這樣連續有兩個catchErrors意味着第二個永遠不會觸發,因為第一個會吞噬錯誤。

您需要在第一個catchError重新拋出該錯誤才能進入第二個錯誤:

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

因此,恐怕您的問題沒有任何意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM