How to mock RxJs Observable Websocket for Unit Tests

元气小坏坏 提交于 2021-01-28 05:45:45

问题


I am creating a web app unsing Angular 4 and RxJs. In one part of my code I am creating a websocket using: Observable.websocket(url); function.

Here is my code:

  /**
   * 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 };
  }

The next thing that I would like to do, is to create an unit test for my websocket. However in order to do this I would need to create a mock websocket so that I can freely send and receive messages from it.

Does anyone knows how to do this? Is it possible to use the Angular MockBackend for this?


回答1:


As OP mentioned the answer was to use spies.

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


来源:https://stackoverflow.com/questions/48584094/how-to-mock-rxjs-observable-websocket-for-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!