Felipe
Felipe

Reputation: 7381

How to mock RxJs Observable Websocket for Unit Tests

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?

Upvotes: 2

Views: 2987

Answers (1)

Mike Tung
Mike Tung

Reputation: 4821

As OP mentioned the answer was to use spies.

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

Upvotes: 3

Related Questions