Rxjs在茉莉花中生效的同步函数中引发错误

问题描述 投票:0回答:1

我有类似]的效果>

  public save$ = createEffect(() =>
    this.actions$.pipe(
      ofType(saveActions.save),
      map((payload) => payload.info),
      switchMap((info) =>
        of(this.service.save(info)).pipe(
          map(() => 
            saveActions.success({ info });
          ),
          catchError((error) =>
           from([saveActions.fail(), noticiations.error({ message: error.key })]);
          )
        )
      )
    )
  );

service.save进行一些操作并返回void,这就是在of中使用switchMap的原因。

此逻辑工作正常。但是现在我正在编写单元测试,

describe((effect) => {
    beforeEach(() => (emitCounter = 0));
    it('should handle error cases', (done) => {
        const error = { key: 'error' };

        service.save.and.throwError(error);
        actions.next(actions.save({ info }));

        effects.save$.pipe(take(2)).subscribe((resp) => {
            expect(service.save).toHaveBeenCalledTimes(1);
            switch (resp.type) {
                case actions.fail.type: {
                    expect(result.type).toBe(saveActions.fail.type);
                    emitCounter++;
                    break;
                }

                case notifications.error.type: {
                    expect(result).toEqual({
                        type: notifications.error.type,
                        message: error.key,
                    });
                    emitCounter++;
                    break;
                }
            }
            done();
        });
        expect(emitCounter).toBe(2);
    });
});


问题是执行程序永远不会进入effects.save$.pipe(take(2)).subscribe((resp) => {内部>

[当我更改service.save以返回Observable<void>,因此从效果中删除of时,执行工作正常。

我有一个类似public save $ = createEffect(()=> this.actions $ .pipe(ofType(saveActions.save),map((payload)=> payload.info),switchMap((info)=>的效果)> of(...

angular rxjs jasmine karma-jasmine
1个回答
0
投票

我认为您必须将of(this.service.save(info))部分替换为此:

new Observable(s => {
  try {
    this.service.save(info);

    s.next();
  } catch (err) {
    s.error(err);
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.