簡體   English   中英

如何為單元測試模擬RxJs可觀察的Websocket

[英]How to mock RxJs Observable Websocket for Unit Tests

我正在使用Angular 4和RxJs創建一個Web應用程序。 在代碼的一部分中,我將使用以下方法創建一個Websocket: Observable.websocket(url); 功能。

這是我的代碼:

  /**
   * Tries to open a websocket connection to a given URL.
   * @param url
   * @param subscription Previous subscription to this socket (it may be necessary to close it before proceeding)
   * @returns an object containing the subscription and the websocket subject.
   */
  private openConnection(url: string, subscription: Subscription): { socket$: WebSocketSubject<any>, subscription: Subscription } {
    const socket$ = Observable.webSocket<string>(url);

    // Make sure we unsubscribe from the previous socket if necessary.
    if (subscription) {
      subscription.unsubscribe();
    }

    // Subscribe the recently created socket. Note: this must be done otherwise the socket won't work.
    const newSubscription = socket$.subscribe(
      (msg: string) => this.handleIncomingMessages(msg),
      (error: Error) => this.handleErrors(error),
      () => this.handleComplete());

    return { socket$: socket$, subscription: newSubscription };
  }

我想做的下一件事是為Websocket創建一個單元測試。 但是,為了做到這一點,我需要創建一個模擬websocket,以便我可以自由地發送和接收來自它的消息。

有誰知道該怎么做? 是否可以為此使用Angular MockBackend

正如OP提到的,答案是使用間諜。

fakeSocket = new Subject<any>(); spyOn(Observable, 'webSocket').and.returnValue(fakeSocket);

暫無
暫無

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

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