如何在可观察的错误中测试抛出

时间:2018-04-18 13:04:11

标签: angular typescript jasmine

在我们的app.component中,我们使用订阅来检测websocket失败。

ngOnInit() {
  this.subscriptions.push(
    this.ws.getData().subscribe(
      (message: any) => { },
      error => {
        this.isOverlayVisible = true;
      },
      () => console.info('Websocket completed'),
    ),
  );

我们希望在发生错误时测试isOverlayVisible设置为true

设定:

websocketDataSubject = new Subject();
ws = jasmine.createSpyObj('ws', ['getData']);
ws.getData.and.returnValue(websocketDataSubject);

测试:

describe('when error is received', () => {
  beforeEach(() => {
    component.isOverlayVisible = false;
    websocketDataSubject.error('any error');
  });

  it('should set isOverlayVisible to true', () => {
    expect(component.isOverlayVisible).toBe(true);
  });
});

但由于抛出了实际错误,测试失败了。

如何在我们的设置中测试此类行为?

为了在讨论中添加更多内容,ws.getData基本上是我们的WebsocketSubject的getter:

public getData(): ReconnectWebsocketSubject<any> {
  return this.ws;
}

和我们的WebsocketSubject:

connect(): void {
    this.socket = new WebSocketSubject(this.wsSubjectConfig);
    this.socket.subscribe(
      m => {
        this.next(m);
      },
      (error: Event) => {
        if (!this.socket) {
          this.reconnect();
        }
      },
    );
  }

  reconnect(): void {
    this.reconnectionObservable = interval(this.reconnectInterval).pipe(
      takeWhile((v, index) => {
        return index < this.reconnectAttempts && !this.socket;
      }),
    );

    this.reconnectionObservable.subscribe(
      () => {
        this.connect();
      },
      null,
      () => {
        this.reconnectionObservable = null;
        if (!this.socket) {
          this.error(new WebsocketReconnectFailureError());

          this.complete();
          this.connectionObserver.complete();
        }
      },
    );
  }

0 个答案:

没有答案
相关问题